node.js Mongoose 创建多个文档
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15400029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mongoose create multiple documents
提问by lostintranslation
I know in the latest version of Mongoose you can pass multiple documents to the create method, or even better in my case an array of documents.
我知道在最新版本的 Mongoose 中,您可以将多个文档传递给 create 方法,或者在我的情况下更好的是传递一个文档数组。
var array = [{ type: 'jelly bean' }, { type: 'snickers' }];
Candy.create(array, function (err, jellybean, snickers) {
if (err) // ...
});
My problem is that the size of the array is dynamic so in the callback it would be helpful to have an array of the created objects.
我的问题是数组的大小是动态的,因此在回调中拥有一个已创建对象的数组会很有帮助。
var array = [{ type: 'jelly bean' }, { type: 'snickers' }, ..... {type: 'N candie'}];
Candy.create(array, function (err, candies) {
if (err) // ...
candies.forEach(function(candy) {
// do some stuff with candies
});
});
Not in the documentation, but is something like this possible?
不在文档中,但这样的事情可能吗?
回答by JohnnyHK
回答by Nebojsa Sapic
With Mongoose v5.1.5, we can use insertMany()method with array passed.
在Mongoose v5.1.5 中,我们可以使用insertMany()方法传递数组。
const array = [
{firstName: "Jelly", lastName: "Bean"},
{firstName: "John", lastName: "Doe"}
];
Model.insertMany(array)
.then(function (docs) {
response.json(docs);
})
.catch(function (err) {
response.status(500).send(err);
});
回答by Soviut
According to this ticketon GitHub, Mongoose 3.9 and 4.0 will return an array if you supply an array and a spread of arguments if you supply a spread when using create().
根据GitHub 上的这张票,如果您在使用create().
回答by dimpiax
by insertfunction of collection db,
example:
通过insert收集数据库的功能,例如:
Model.collection.insert(array, (err, list) => {
if (err) throw err;
console.log('list:', list);
});

