1

Consider this schema:

var UserSchema = new Schema({
    ...
    user_id: {type:String},
    previous_selection: {type:String},
    current_selection: {type:String}
});

I need to write a function, which will update the value of previous_selection with the value of current_selection for the given user_id.

Is there any way of doing this with findOneAndUpdate?

Something like -

MyModel.findOneAndUpdate(
        { user_id: id }, 
        { $set: {"previous_selection": current_selection }},
        {}, 
        callback
);

Or is there a better way to implement this? Will I have to do a find() and then update?

Mallika Khullar
  • 1,725
  • 3
  • 22
  • 37
  • you cannot update a field with another one in single update you have to call a find method to accomplish this – wrangler Nov 07 '17 at 12:07

1 Answers1

4

As per your concern you can do this to update entire collection.

db.MyModel.find({}).snapshot().forEach(
function (elem) {
    db.MyModel.update(
        {
            _id: elem._id
        },
        {
            $set: {
                "previous_selection": elem.current_selection
            }
        }
    );
});

else you can find by id and can update with respective current_selection.

Srikar Jammi
  • 115
  • 8