Matheus
Matheus

Reputation: 321

UpdateMany in mongoose not working but directly in mongodb works fine

I'm trying to make update/insert in mongoose. I make some request and the result is ( exemple )

let obj = [
    {name: aaa,age: 10},
    {name: bbb,age: 11},
    {name: ccc,age: 12},
]

I'm trying to update all documents, but if they dont exist, create them.

I tried do:

updateMany({}, {$set: {nome:"obj.$.name", idade: "obj.$.age"}}, {upsert:true})

But, nothing happens, I try to make another test in mongoose, more simple, like this:

<model-context>.updateMany({},{$set: {name: 'abc'}},{upsert: true})

Didnt work, so I make the same update direct in mongodb

db.context.updateMany({},{$set: {name: 'abc'}},{upsert: true})

And worked, I need to do something more in mongoose to work?

NOTE: I can use createMany in mongoose, works fine.

Upvotes: 3

Views: 6039

Answers (1)

Matheus
Matheus

Reputation: 321

I resolved the problem, i need to pass a function in argument of updateMany

for(let n of obj){
   <context>.update({name: n.name}, {$set: {'age':n.age}}, {upsert: true},  
(err, doc)=>{
    if(err) console.log(err);
    console.log(doc)
 })
}

Upvotes: 1

Related Questions