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

标签 javascript node.js mongodb mongoose database

背景: 我必须根据我零控制的发布请求创建或更新文档。我正在调用函数 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 命令。

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

关于javascript - 如何使用 mongo/mongoose 通过 _id 以外的字段查找文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31170995/

相关文章:

javascript - 数千个对象会损害性能吗

mongodb - 为什么我的 mongo 集合在 azure ubuntu 实例上被删除?

javascript - 渲染多个子组件的最佳方式

javascript - 如何判断复选框是否被选中?

javascript - 如何禁用特定页面上的js脚本?

javascript - 如何检测人类打字并防止在聊天网站上发送垃圾邮件

javascript - Mongoose :找到最近的文件

javascript - express 4 的异步包装函数不会捕获错误

mongodb - 是否可以在 MongoDB 的单个事务中执行多个数据库操作?

javascript - 无法散列密码并将其设置为 mongodb 模式中的字段