2

I want to save array of objects in MongoDB in my Meteor app and I'm also using Meteor astronomy for manage Mongo collection

My array of objects like this

[
    {
        "id" : "aaaa1",
        "make" : "toyota",
        "year" : "2005",
        "model" : "prado",
    },
    {
        "id" : "aaaa2",
        "make" : "toyota",
        "year" : "2005;2006",
        "model" : "fortuner",
    },
    {
        "id" : "aaaa3",
        "make" : "toyota",
        "year" : "2005;2006;2007;2008",
        "model" : "axio",

    },

]

I used map function to loop through the array and save data, but it only saves the last record. Here is my code

array.map((row) => {
  console.log(row.type);
  vehicleDb.set({
    make: row.make,
    year: row.year,
    model: row.model,

  });
  vehicleDb.save( function (error) {
    // console.log(error);
  });
});
3

3 Answers 3

0

You are using ".set" to save elements into an array, you need to "push" then into the array. Here's a list of MongoDB array operators: https://docs.mongodb.com/manual/reference/operator/update-array/

Sign up to request clarification or add additional context in comments.

Comments

0

I assume that vehicleDb is your schema/model because you used vehicleDb.save. If my assumption is correct then you can try it:

array.map((row) => {
  console.log(row);
  var newVehicle = new vehicleDb(row);
  newVehicle.save( function (error, doc) {
    // console.log(error);
    // console.log(doc)
  });
});

if vehicleDb is not your model then added your schema in your question and I will update my answer

Comments

0
array.map(async (row) => {
  const Notify = new Notification({ attributeName:row.attributeName, attributeName:row.attributeName})
  var save=await Notify.save()
});

In my case it is not working when passing a whole object for saving in a document.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.