DarkLeafyGreen
DarkLeafyGreen

Reputation: 70426

Check if document exists in mongodb

This is how I check if a document exists:

var query = {};

if (req.body.id) {
    query._id = {
        $ne: new require('mongodb').ObjectID.createFromHexString(req.body.id)
    };
}

Creditor.native(function(err, collection) {
    collection.find({
        $or: [{
                name: req.body.name
            }, {
                sapId: req.body.sapId
            },
            query
        ]
    }).limit(-1).toArray(function(err, creditors) {
        if (creditors.length > 0) {
            return res.send(JSON.stringify({
                'message': 'creditor_exists'
            }), 409);
        } else {
            return next();
        }
    })
});

To avoid that multiple documents exist with the same name or/and the same sapID I do this check on every creation/update of a document.

E.g. I want to update this document and give it a different name

{
    name: 'Foo',
    sapId: 123456,
    id: '541ab60f07a955f447a315e4'
}

But when I log the creditors variable I get this:

[{
    _id: 541a89a9bcf55f5a45c6b648,
    name: 'Bar',
    sapId: 3454345
}]

But the query should only match the same sapID/name. However there totally not the same. Is my query wrong?

Upvotes: 2

Views: 4192

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312035

You're currently finding docs where name matches OR sapId matches OR _id doesn't match. So that last clause is what's pulling in the doc you're seeing.

You probably mean to find docs where (name matches OR sapId matches) AND _id doesn't match.

collection.find({ $and: [
    query,
    { $or: [{
            name: req.body.name
        }, {
            sapId: req.body.sapId
        }
    ] } ]
})

Or more simply:

collection.find({
    _id: { $ne: require('mongodb').ObjectID.createFromHexString(req.body.id) },
    $or: [{
            name: req.body.name
        }, {
            sapId: req.body.sapId
        }
    ]
})

Upvotes: 2

Related Questions