简体   繁体   中英

How to update every single document in a MongoDB collection?

I know this is probably a duplicate but the solutions on this post didn't work for me so I decided to repeat it.

I am trying to put a new field on every single document in my database without loosing any data. I searched around a lot and found this code.

           let res = await client.guildData.updateMany({  }, {$set: {testData: false}}, { upsert: true, multi: true })

            console.log(res.nModified)

However, when I run this code, nothing happens and 0 logs in the console that it didn't find anything to update, when in reality there is 9 documents it should update.

Does anybody know how to fix this?

In Mongoose you don't need to specify the $set . So you can replace {$set: {testData: false}} with just {testData: false} Documentation

Model.updateMany({}, { field: 'value'}, {upsert: true})

This is basically what I originally posted, but @Vishnu suggested I added it to the schema and changed the code to this and now it works fine:)

let thisThing = await client.guildData.updateMany( { }, {$set:{ guildWhiteList: [] }}, { useFindAndModify: false});

            console.log(thisThing)

Thanks for your help everyone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM