检查mongodb中是否存在文档

检查mongodb中是否存在文档,mongodb,node-mongodb-native,Mongodb,Node Mongodb Native,这是我检查文档是否存在的方式: 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: [{

这是我检查文档是否存在的方式:

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();
        }
    })
});
为了避免存在多个具有相同名称或/和相同sapID的文档,我会在每次创建/更新文档时进行此检查

例如,我想更新此文档并为其指定一个不同的名称

{
    name: 'Foo',
    sapId: 123456,
    id: '541ab60f07a955f447a315e4'
}
但当我记录债权人变量时,我得到:

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

但是查询应该只匹配相同的sapID/名称。然而,情况完全不同。我的查询错了吗?

您当前正在查找
名称
匹配或
sapId
匹配或
\u id
不匹配的文档。最后一条就是你看到的文件中的内容

您可能想查找(
name
匹配或
sapId
匹配)
\u id
不匹配的文档

collection.find({$and:[
查询
{$or:[{
名称:req.body.name
}, {
sapId:req.body.sapId
}
] } ]
})
或者更简单地说:

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