I can’t update many data(Array data made of Object type) in MongoDB plz help me
import {MongoClient, ObjectId} from "mongodb";
async function handler(req, res) {
if (req.method === "POST") {
const data = req.body;
const client = await MongoClient.connect("mongodb+srv:myURL")
const db = client.db();
const postItCollection = db.collection("tableData");
const result = await postItCollection.updateMany({_id: new ObjectId(data.id)}, {$set : {
contents:data.contents,
width:data.width,
height:data.height,
positionX:data.positionX,
positionY:data.positionY,
positionZ:data.positionZ,
}}, {upsert: true});
client.close();
res.status(201).json({message: "success"})
}
}
export default handler;
For example, I have array data of length 2.
It is made of object data that needs to be updated.
If i use above code all prop values entered null…
How can I update multiple array data at once?
[
{
id: 0.5849485030977961,
positionX: 0,
positionY: 0,
positionZ: 10,
width: 200,
height: 220,
userId: 'userid',
style: '',
pinned: false,
contents: { titles: [Array], contents: [Array] }
},
{
id: 0.06866579058492106,
positionX: 0,
positionY: 0,
positionZ: 10,
width: 200,
height: 220,
userId: 'userid',
style: '',
pinned: false,
contents: { titles: [Array], contents: [Array] }
}
]
If I have the above data,
I would like to upload it according to each property in Mongo db
3
Answers
Hi I solved 🤣 The key is
for loop
But If u have a cleaner leaner code, please let me know 🙏
Please refer to this documentation in MongoDB in order to update many in single query.
https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkWrite/
You can simplify your code by using
findByIdAndUpdate
: