These are chat archives for Automattic/mongoose

12th
Aug 2018
Kev
@lineus
Aug 12 2018 11:43
that's weird @hillct it works for me
André Bomark
@ZwiFTi
Aug 12 2018 12:03
Is there a way I can have multiple objects in an array, then update them all at the same time in mongoose? How would I go about this
Kev
@lineus
Aug 12 2018 12:04
@ZwiFTi can you describe what you're trying to accomplish in more detail?
André Bomark
@ZwiFTi
Aug 12 2018 12:14
Something like this @lineus : A batch update
let listOfDocuments = [{},{},{},{},{},{}]

db.collection.updateMany(listOfDocuments)
So that I don't do multiple posts to server per document, and only one for them all
Kev
@lineus
Aug 12 2018 12:17
mongoose Model has an updateMany method that applies the update doc to all of the documents that match the conditional object.
Kev
@lineus
Aug 12 2018 12:24
Kev
@lineus
Aug 12 2018 12:31
if each doc requires a unique update object, you can use Model.bulkWrite with an array of objects representing the updates.
André Bomark
@ZwiFTi
Aug 12 2018 12:47
@lineus Thank you! Two questions: In the first example, the only thing that has to match is the ids? And, are they equal in performance?
Kev
@lineus
Aug 12 2018 12:56
@ZwiFTi yeah, you can match on just a single field. I'm not sure about performance, you'll have to play around with your specific situation and see :smile:
André Bomark
@ZwiFTi
Aug 12 2018 13:40
@lineus I am ALMOST there.. I have one related problem.. Why is updates an object for me? I need it to be an array:
let updates = []

// req.body is an object -> fill objs to array
for (var key in req.body) {
    if(req.body.hasOwnProperty(key)){
        updates.push(req.body[key])
    }
}

console.log(updates) // [{},{}]
console.log(typeof(updates)) // object

Card.bulkWrite(updates); // Invalid op passed to `bulkWrite()`
I am sending an array of objects with req.body
Kev
@lineus
Aug 12 2018 14:01
@ZwiFTi typeof returns 'object' for arrays
gitter: node
> typeof []
'object'
> gitter:
if you want to see if it's an array use Array.isArray(x)
> gitter: node
> Array.isArray([])
true
> gitter:
Kev
@lineus
Aug 12 2018 14:07
the shape of the objects in the array passed into bulkWrite() is outlined in the docs, you have to pass in an object like:
{ updateOne: { filter: {}, update: {} } }
where updateOne could also be insertOne or updateMany etc. docs here
hillct
@hillct
Aug 12 2018 21:13
@lineus thanks for your earlier reply. I have no explanation for the necesity of my solution, or why it worked for you without that change. What I found i had to do was rename ‘items’ in this line: { $group: { _id: 1, items: { $addToSet: '$tag_list' } } } to virtually anything else, and I was able to reference that property. I’m baffled as to why ‘items’ might be a reserved word, or for that matter what module might be using it in that scope. I presume you had success because you were working with somewhat more stripped down code than I, which I suppose speaks poorly of my debugging efforts.