skip to Main Content

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
example

3

Answers


  1. Chosen as BEST ANSWER
    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://URL")
            const db = client.db();
            const postItCollection = db.collection("tableData");
            for(let i=0; i<data.length; i++){
            const result = await postItCollection.updateMany({_id: new ObjectId(data[i].id)}, {$set : {
                    pinned:data[i].pinned,
                    style:data[i].style,
                    userId:data[i].userId,
                    contents:data[i].contents,
                    width:data[i].width,
                    height:data[i].height,
                    positionX:data[i].positionX,
                    positionY:data[i].positionY,
                    positionZ:data[i].positionZ,
                }}, {upsert: true});
            }
            client.close();
            res.status(201).json({message: "success"})
        }
    }
    
    export default handler;
    

    Hi I solved 🤣 The key is for loop

    But If u have a cleaner leaner code, please let me know 🙏


  2. 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/

    Login or Signup to reply.
  3. You can simplify your code by using findByIdAndUpdate:

    async function handler(req, res) {
      if (req.method === 'POST') {
        const data = req.body;
        const client = await MongoClient.connect('mongodb+srv://URL');
        const db = client.db();
        const postItCollection = db.collection('tableData');
        for (const d of data) {
          await postItCollection.findByIdAndUpdate(new ObjectId(d.id), d, {
            upsert: true,
          });
        }
        client.close();
        res.status(201).json({ message: 'success' });
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search