背景:
我必须根据我零控制的发布请求创建或更新文档。我正在调用函数 updateOrCreate()
问题:
<小时/>How can I properly find a document by an field called
nuid
without using_id
in mongo/mongoose
负载示例:
curl -H "Content-Type: application/json" -X POST -d '{"participant":{"nuid":"98ASDF988SDF89SDF89989SDF9898"}}' http://localhost:9000/api/things
事物 Controller :
exports.updateOrCreate = function(req, res) {
//Thing.findByNuid() will not work but it will explain what i'm trying to accomplish
/**
Thing.findByNuid(req.body.participant.nuid, function (err, thing) {
if (err) { return handleError(res, err); }
if(!thing) {
Thing.create(req.body.participant, function(err, thing) {
if(err) { return handleError(res, err); }
});
}
var updated = _.merge(thing, req.body.participant);
updated.save(function (err) {
if (err) { return handleError(res, err); }
});
});
**/
//this block will fetch all the things that have nuids but that seems really heavy and awful practice
Thing.find({'nuid':req.body.participant.nuid}, function(err, thing){
console.log(thing);
});
// This block is here to communicate this will create a new thing as expected.
Thing.create(req.body.participant, function(err, thing) {
if(err) { return handleError(res, err); }
});
}
架构
var ThingSchema = new Schema({
nuid: String
});
更新:
var query = {"nuid": req.body.participant.nuid};
var update = {nuid: 'heyyy'};
Thing.findOneAndUpdate(
query,
update,
{upsert: true},
function(err, thing){
console.log(thing, "thing");
console.log(err, "err");
}
);
最佳答案
我会使用findOneAndUpdate
首先,然后根据结果执行插入
。 findOneAndUpdate
使用 mongoDB findAndModify
命令。
您还应该查看它的 new
和 upsert
选项,如果找不到,它们会创建一个文档。
关于javascript - 如何使用 mongo/mongoose 通过 _id 以外的字段查找文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31170995/