【问题标题】:How to find a document by an field other than _id using mongo/mongoose如何使用 mongo/mongoose 通过 _id 以外的字段查找文档
【发布时间】:2015-09-19 04:21:22
【问题描述】:

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

问题:

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


示例负载:

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

【问题讨论】:

    标签: javascript node.js mongodb mongoose database


    【解决方案1】:

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

    您还应该查看它的newupsert 选项,如果没有找到它会创建一个文档。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-17
      • 2014-10-16
      • 2016-09-17
      • 2012-05-30
      • 2020-04-28
      • 2021-01-20
      • 1970-01-01
      • 2016-03-24
      相关资源
      最近更新 更多