Reputation: 432
There is a clients collection which is structured like this:
const ClientSchema = mongoose.Schema({
name: {
type: String,
required: true,
},
region: {
type: String,
required: true,
},
balance: {
type: Number,
default: 0,
},
phone: {
type: Number,
unique: true,
required: true,
},
});
and here is the sample data I have stored:
[
{_id: 'someID1', name: 'Joe Smith', region: 'USA', balance: 0, phone: 123456789},
{_id: 'someID2', name: 'Kim Laws', region: 'CANADA', balance: 100, phone: 342345345},
{_id: 'someID3', name: 'Dandy Cruz', region: 'EUROPE', balance: 2000, phone: 4536456456},
]
Data is displayed as a table on the client app, and users can modify the data on the table (something like a spreadsheet).
So suppose, after user messes around with the initial data, it mutated to something like this:
[
{_id: 'someID1', name: 'Freedom Brights', region: 'AFRICA', balance: 2000, phone: 123456789},
{_id: 'someID2', name: 'Kim Sun', region: 'ASIA', balance: 0, phone: 342345345},
{_id: 'someID3', name: 'Dandy Cruz', region: 'EUROPE', balance: 2000, phone: 4536456456},
]
How would you update all these records on a single request with mongoose?
I've tried some googling and found methods like update()
and updateMany()
but all the examples out there doesn't exactly show how to approach this problem.
I would highly appreciate any help. Thank you!
Upvotes: 0
Views: 76
Reputation: 108
you can use the bulkwrite
db.collection.bulkWrite( [
{ updateMany :
{
"filter" : <document>,
"update" : <document or pipeline>, // Changed in MongoDB 4.2
"upsert" : <boolean>,
"collation": <document>, // Available starting in 3.4
"arrayFilters": [ <filterdocument1>, ... ], // Available starting in 3.6
"hint": <document|string> // Available starting in 4.2.1
}
}
] )
also the document https://mongoosejs.com/docs/api.html#model_Model.bulkWrite
Upvotes: 1