检查mongodb中是否存在文档

时间:2014-09-18 11:39:12

标签: 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: [{
                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的文档,我会检查每次创建/更新文档。

E.g。我想更新此文档并给它一个不同的名称

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

但是当我记录债权人变量时,我得到了这个:

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

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

1 个答案:

答案 0 :(得分:2)

您目前正在查找name匹配或sapId匹配或_id匹配的文档。所以最后一个条款就是你所看到的文档。

您可能需要找到哪些文档(name匹配或sapId匹配) AND _id不匹配。

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

或更简单:

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