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);
  });
});
Kyll
  • 7,036
  • 7
  • 41
  • 64
sasy
  • 493
  • 3
  • 9
  • 21

3 Answers3

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/

HoefMeistert
  • 1,190
  • 8
  • 17
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

Shaishab Roy
  • 16,335
  • 7
  • 50
  • 68
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.

antokhio
  • 1,497
  • 2
  • 11
  • 16