【问题标题】:Save array of object in MongoDB在 MongoDB 中保存对象数组
【发布时间】:2017-01-13 10:21:00
【问题描述】:

我想在我的 Meteor 应用程序中保存 MongoDB 中的对象数组,并且我还使用 Meteor 天文学来管理 Mongo 集合

我这样的对象数组

[
    {
        "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",

    },

]

我使用 map 函数循环遍历数组并保存数据,但它只保存最后一条记录。这是我的代码

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);
  });
});

【问题讨论】:

标签: mongodb meteor astronomy


【解决方案1】:

您正在使用“.set”将元素保存到数组中,您需要“推”然后到数组中。 以下是 MongoDB 数组运算符列表:https://docs.mongodb.com/manual/reference/operator/update-array/

【讨论】:

    【解决方案2】:

    我假设vehicleDb 是您的架构/模型,因为您使用了vehicleDb.save。如果我的假设是正确的,那么你可以试试:

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

    如果 vehicleDb 不是您的模型,则在您的问题中添加您的架构,我会更新我的答案

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      • 2021-08-13
      • 2020-12-19
      相关资源
      最近更新 更多