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?

1
  • you cannot update a field with another one in single update you have to call a find method to accomplish this Commented Nov 7, 2017 at 12:07

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

What does .snapshot() do?
It simply prevents returning the doc more than once.
Nice; but returning the same doc more than once, or duplicates?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.