在MongoDB,Node.js中使用一个Success回调Mongoose保存多个实体

时间:2014-09-09 12:26:53

标签: node.js mongodb

我有一个Mongoose模型产品

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

var mongooseProductModel = new products(newProduct);

使用Mongoose进行所有设置我可以通过调用

来保存产品
mongooseProductModel.save(function(err)){
}

当我想创建一个产品时,这很好用。但是,如果我想一次创建多个产品呢?与实体框架类似,我们可以向DBContext提交实体集合,并且调用save将使用单个保存产品调用保存所有实体。是否有可能用Mongoose实现这一目标?

1 个答案:

答案 0 :(得分:0)

我认为你可以调用异步保存功能。 这是代码示例,它使用来自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对象数组上的map调用该函数,迭代器函数将从每个项创建mongoose实体