Node.js Mongoose创建多个文档

Node.js Mongoose创建多个文档,node.js,mongoose,Node.js,Mongoose,我知道在最新版本的Mongoose中,您可以将多个文档传递给create方法,在我的例子中,甚至可以传递一个文档数组 var array = [{ type: 'jelly bean' }, { type: 'snickers' }]; Candy.create(array, function (err, jellybean, snickers) { if (err) // ... }); 我的问题是数组的大小是动态的,所以在回调中创建一个对象数组会很有帮助 var array = [

我知道在最新版本的Mongoose中,您可以将多个文档传递给create方法,在我的例子中,甚至可以传递一个文档数组

var array = [{ type: 'jelly bean' }, { type: 'snickers' }];
Candy.create(array, function (err, jellybean, snickers) {
    if (err) // ...
});
我的问题是数组的大小是动态的,所以在回调中创建一个对象数组会很有帮助

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

文档中没有,但这样做可能吗?

您可以通过访问回调的参数变量列表。所以你可以这样做:

Candy.create(array, function (err) {
    if (err) // ...

    for (var i=1; i<arguments.length; ++i) {
        var candy = arguments[i];
        // do some stuff with candy
    }
});
Candy.create(数组,函数(err){
如果(错误)/。。。

对于(var i=1;i根据GitHub上的说明,Mongoose 3.9和4.0将返回一个数组,如果您在使用collection db的
create()
插入
函数时提供一个排列,则返回一个排列参数,
例如:

使用,我们可以使用传递数组的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);
    });

由于Mongoose v5,您可以使用
insertMany
据了解,它比
快。create()

用于验证文档数组并将其插入的快捷方式 MongoDB,如果它们都有效。此函数比
.create()
因为它只向服务器发送一个操作,而不是为服务器发送一个操作 每份文件

完整示例:

const mongoose = require('mongoose'); 
  
// Database connection 
mongoose.connect('mongodb://localhost:27017/databasename', { 
    useNewUrlParser: true, 
    useCreateIndex: true, 
    useUnifiedTopology: true
}); 
  
// User model 
const User = mongoose.model('User', { 
    name: { type: String }, 
    age: { type: Number } 
}); 


// Function call, here is your snippet
User.insertMany([ 
    { name: 'Gourav', age: 20}, 
    { name: 'Kartik', age: 20}, 
    { name: 'Niharika', age: 20} 
]).then(function(){ 
    console.log("Data inserted")  // Success 
}).catch(function(error){ 
    console.log(error)      // Failure 
});

哈哈,忘了这一切。非常感谢。
const mongoose = require('mongoose'); 
  
// Database connection 
mongoose.connect('mongodb://localhost:27017/databasename', { 
    useNewUrlParser: true, 
    useCreateIndex: true, 
    useUnifiedTopology: true
}); 
  
// User model 
const User = mongoose.model('User', { 
    name: { type: String }, 
    age: { type: Number } 
}); 


// Function call, here is your snippet
User.insertMany([ 
    { name: 'Gourav', age: 20}, 
    { name: 'Kartik', age: 20}, 
    { name: 'Niharika', age: 20} 
]).then(function(){ 
    console.log("Data inserted")  // Success 
}).catch(function(error){ 
    console.log(error)      // Failure 
});