【问题标题】:Saving more than one entity with one Success callback Mongoose in MongoDB, Node.js [duplicate]在MongoDB,Node.js中使用一个成功回调Mongoose保存多个实体[重复]
【发布时间】:2014-11-02 21:01:42
【问题描述】:

我有一个 Mongoose 模型产品,其中

var newProduct : {
   name : "Product 1",
   color : "red",
   categoryId : 1023,
   isAvailbale : true
}

var mongooseProductModel = new products(newProduct);

有了 Mongoose 的所有设置,我可以通过调用来保存产品

mongooseProductModel.save(function(err)){
}

当我只想创建一个产品时,这很好用。但是,如果我想一次创建多个产品怎么办?就像在实体框架中一样,我们可以向 DBContext 提交实体集合,调用 save 将通过单个 save 产品调用保存所有实体。是否有可能使用 Mongoose 实现这一目标?

【问题讨论】:

  • 我认为不是重复的。另一个线程中接受的解决方案不符合我的目的。

标签: node.js mongodb


【解决方案1】:

我认为你可以调用异步保存函数。 这是代码示例,它使用来自 JSON 对象的数据预填充数据库 https://github.com/vodolaz095/hunt/blob/master/examples/lib/populateDatabase.js

var preys = [
  {
    'name': 'Alan Schaefer',
    'scored': false,
    'priority': 10
  },
  {
    'name': 'George Dillon',
    'scored': true,
    'priority': 9
  },
  {
    'name': 'Rick Hawkins',
    'scored': true,
    'priority': 8
  },
  {
    'name': 'Blain Cooper',
    'scored': true,
    'priority': 7
  },
  {
    'name': 'Billy Sole',
    'scored': true,
    'priority': 6
  },
  {
    'name': 'Anna Goncalves',
    'scored': false,
    'priority': 0
  },
];

module.exports = exports = function (hunt) {
  //populating the trophies' collection in database
  hunt.model.Trophy.remove({}, function (error) {
    if (error) {
      throw error;
    } else {
      hunt.async.map(preys, function (prey, cb) {
        hunt.model.Trophy.create(prey, cb);
      }, function (error, preysSaved) {
        if (error) {
          throw error;
        } else {
          console.log('' + preysSaved.length + ' trophies recorded.');
        }
      });
    }
  });
};

此代码通过https://github.com/caolan/async#map 函数工作。

所以,您可以通过 JSON 对象数组上的映射调用该函数,迭代器函数将从每个对象创建 mongoose 实体

【讨论】:

    猜你喜欢
    • 2014-09-14
    • 2016-05-01
    • 1970-01-01
    • 2023-04-10
    • 2011-09-22
    • 2012-03-22
    • 2016-12-11
    • 2016-11-16
    • 1970-01-01
    相关资源
    最近更新 更多