我认为你可以调用异步保存函数。
这是代码示例,它使用来自 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 实体