node.js - Mongoose:FindOneAndUpdate(),带有来自字段引用的查询

标签 node.js mongodb mongoose

var WorkstationSchema = new Schema({
    tag: { type : String },
    address : { type : String , unique : true, required : true },
    status: { type : String , required : true },
});


    var ProblemSchema = new Schema({
        type: { type: Number, default: 0 },
        status: { type: Number, default: 0 },
        dateCreated: { type: String, trim: true, default: '' },
        workstation: {type: Schema.ObjectId, ref: 'Workstation'},
    });

    conditions = {type: problemType, status: 0, 'workstation.address': remote64};
    update = {status: 1};

    ProblemSchema.findOneAndUpdate(conditions, update, options).populate('workstation', 'address').exec(function (err, problem) {
          if(err){
             //do something
          } else {
                console.log(problem);
              }

    });

这些是我的实体,我需要找到具有此地址的工作站的问题并更新问题状态。

我怎样才能做到这一点?

最佳答案

您可以在没有 workstation.address 的情况下应用匹配条件来查找问题并填充,然后匹配 workstation.address 来更新状态。

conditions = {type: problemType, status: 0};

ProblemSchema.find(conditions).populate("workstation", "address").exec(function(error, docs){ 
  docs.forEach(function (problem) {
    if(problem.workstation && problem.workstation.address === remote64) {
      problem.status = 1;
      problem.save(function(err, doc) {
        if(err){
          //do something
        } else {
          console.log(doc);
        }
      });
    }
  });
});

关于node.js - Mongoose:FindOneAndUpdate(),带有来自字段引用的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39648391/

相关文章:

javascript - 在浏览器中使用浏览器化的 NodeJS 文件

node.js - 如何在 strapi 中使用其他数据库连接?

javascript - Mongoose 和 Node 查询的时机

node.js - 如何在 Mongoose 模式中使用项目的值

mongodb - 带有嵌入式 mongodb 的 gitlab 管道

node.js - 如何从 Mongoose 查询中检索值

javascript - Node : ShellJS not working with command line tools

date - 如何使用 Node.js 和 Mongoose 查询日期?

客户端 JavaScript 代码替换

mongodb - db.createUser() 停止运行