Home > Net >  How to save an existing object in a collection using Mongoose?
How to save an existing object in a collection using Mongoose?

Time:10-29

The below JSON is an example of what I would like to save my MongoDB collection, where the keys should be used as _id's.

I can only think of an exceedingly complicated way to do this, where I would loop the object and sub-loop the nested objects and insert the _id's manually:

const customerObj = await customerDocument.create({ _id: '5434', ...customerColl['5434'] });

I have 10000 of these, so it can't be done by hand.

Question

How to save an existing object like this in a collection using Mongoose?

{
   "5434": {
      "name": "test 1",
      "status": "active",
      "address": {
         "1467": {
            "comment": ""
         }
      },
      "contact": {
         "3235": {
            "firstname": ""
         }
      }
   },
   "6000": {
      "name": "test2",
      "status": "active",
      "address": {
         "1467": {
            "comment": ""
         }
      },
      "contact": {
         "3235": {
            "firstname": ""
         }
      }
   }
}

CodePudding user response:

You should be able to use a for-in loop and enumerate the values like this:

for (const id in customerColl) {
    await customerDocument.create({ _id: id, ...customerColl[id] });
}

However, since you have 10000 objects, this could be pretty slow... Thankfully, mongoose allows us to bulk insert/write:

const docs = Object.keys(customerColl) // get the keys... kinda like for-in loop
    .map((id) => ({ _id: id, ...customerColl[id] })); // map to docs

await customerDocument.insertMany(docs);
  • Related