Search code examples
mongodbnode-mongodb-native

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?


Solution

  • 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
            }
        ]
    })