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

时间:2015-07-01 20:25:49

标签: javascript node.js mongodb mongoose database

背景 我必须根据我无法控制的发布请求创建或更新文档。我正在调用函数updateOrCreate()

问题:

  

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

示例有效负载:

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

  });
}

模式

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

1 个答案:

答案 0 :(得分:1)

我首先使用findOneAndUpdate,然后根据结果执行insertfindOneAndUpdate使用mongoDB findAndModify命令。

您还应该看看new& upsert选项,如果找不到则会创建文档。