How do update a specific field in mongoose?

我们两清 提交于 2019-12-08 20:25:52

问题


I have a data set which is

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

I want to find a specific job's _id and update a specific candidates' field such as { _id: 123, user: 12345, status: "In Progress" }

The url for this operation is ---> localhost:3000/apply/:job_id/user_id

For example

Let say that this is the current saved data in job 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 
  }

How do i update only a specific field let say status field that belong to a certain candidates' _id in mongodb, Here's my attempt

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

I will get this error If I use the above operation.

MongoError: The positional operator did not find the match needed from the query. Unexpanded update: candidates.$.status


回答1:


$ is the solution:

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


来源:https://stackoverflow.com/questions/33742316/how-do-update-a-specific-field-in-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!