【问题标题】:How do update a specific field in mongoose?如何更新猫鼬中的特定字段?
【发布时间】:2016-02-17 23:03:39
【问题描述】:

我有一个数据集

var JobSchema = Schema({
  candidates: [{
    user: { type: Schema.Types.ObjectId, ref: 'User'},
    status: { type: String, default: 'In Progress' },
  }]
});

我想查找特定的job's _id 并更新特定候选人的字段,例如{ _id: 123, user: 12345, status: "In Progress" }

这个操作的url是--->localhost:3000/apply/:job_id/user_id

例如

假设这是作业mongodb中当前保存的数据

  { 
   "_id" : 123, ---> job_id

   "candidates" : 
     [{ 
        "_id" : 234 , 
        "user": 345 , --> user_id
        "status" : "In Progress" 
     }, 

       { 
        "_id" : 345 , 
        "user": 678 , --> user_id
        "status" : "In Progress" 
      }]
    "__v" : 0 
  }

我如何只更新一个特定的字段,比如说 status 属于某个候选人的字段 _id 在 mongodb,这是我的尝试

          Job.update(
                    {
                        _id: req.params.job_id,
                    },
                    {
                        $set: {'candidates.$.status': 'Accepted'} ,
                    }, function(err, count) {
                        if (err) return next(err);
                        callback(err, count);
                    });

如果我使用上面的操作,我会得到这个错误。

MongoError:位置运算符未从查询中找到所需的匹配项。未扩展更新:candidate.$.status

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query


    【解决方案1】:

    $ 是解决方案:

    Job.update(
        { 
            _id: found._id, 
            'candidates.user': req.params.user_id
        },
        {
            $set: { 'candidates.$.status': 'Accepted'} },
        }, function(err, count) {
               if (err) return next(err);
               callback(err, count);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-28
      • 2021-04-17
      • 2016-09-01
      • 1970-01-01
      • 2018-08-26
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多