首页 文章

如何使用mongo / mongoose通过_id以外的字段查找文档

提问于
浏览
0

Background: 我必须根据我无法控制的帖子请求创建或更新文档 . 我正在调用函数 updateOrCreate()

问题:

如何在不使用mongo / mongoose中的_id的情况下通过名为nuid的字段正确查找文档


example payload:

curl -H "Content-Type: application/json" -X POST -d '{"participant":{"nuid":"98ASDF988SDF89SDF89989SDF9898"}}' http://localhost:9000/api/things

thing.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); }

  });
}

Schema

var ThingSchema = new Schema({
  nuid: String
});

UPDATE:

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");
      }
  );

1 回答

  • 1

    我首先使用findOneAndUpdate然后根据结果做 insert . findOneAndUpdate 使用mongoDB findAndModify 命令 .

    您还应该查看它的 newupsert 选项,如果找不到则会创建文档 .

相关问题