0

Given array of objects :

const array = [{_id: 1, name: 'one'}, {_id: 2, name: 'two'}]

How do you construct a query so that it will update name field for each document in DB where document's id equals _id in array object?

This must be done in a single query. Query must use mongoDB node driver syntax.

for example:

// in DB : [{_id: 1, name: null, _id: 2, name: null }]
db.collection('sprints').update(....).then(...)
// after operation:
// in DB: [{_id: 1, name: "one", _id: 2, name: "two" }]

1 Answer 1

1

have you tried a construct like this:

Promise.all(array.map(entry =>
    db.collection('sprints').findOneAndUpdate({ _id: entry._id }, { name: entry.name }).save()
)).then(...);

its not the direct way but worked for me (in a test case)

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

5 Comments

Is this really the only way ? this will execute as many queries as elements in the array :(
In theory its the only way. Maybe there is a function for that directly but i couldnt find it in the docs. But in the end mongoose will do a single query for each entry so it doesn't matter anyway. But you re right its definitly not a clean construct
Your query might be ok for me for now ... However I have other keys on sprint objects ... and they get overwritten with object that has only _id & name ... could you modify your query, so that only name would be modified (preserving any other keys) ?
modified with db.collection('sprints').findOneAndUpdate({ _id: new ObjectID(sprint._id) }, { $set : { name: sprint.name} }) . to preserve other keys.
will wait to see if anybody can give a single query solution, if not I'll accept your answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.