How to update a specific field in mongoose?

I have a dataset that

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

I want to find a specific job _id and update the field of specific candidates, for example { _id: 123, user: 12345, status: "In Progress" }

URL for this operation ---> localhost:3000/apply/:job_id/user_id

for instance

Say this is the current saved data in the mongodb job

  { "_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 to update only a specific field, say, a status field belonging to certain _id candidates in mongodb, Here is 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 positioning operator did not find the match needed for the request. Unexpanded update: candidates. $. Status

+5
source share
1 answer

$ is a 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); }); 
+9
source

Source: https://habr.com/ru/post/1236072/


All Articles