我知道在最新版本的Mongoose中你可以将多个文件传递给create方法,或者在我的情况下甚至可以更好地传递一组文档.
var array = [{ type: 'jelly bean' }, { type: 'snickers' }];
Candy.create(array, function (err, jellybean, snickers) {
if (err) // ...
});
Run Code Online (Sandbox Code Playgroud)
我的问题是数组的大小是动态的,所以在回调中有一个创建对象的数组会很有帮助.
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
});
});
Run Code Online (Sandbox Code Playgroud)
不在文档中,但是这样可能吗?
Joh*_*yHK 39
您可以通过访问回调的变量参数列表arguments.所以你可以这样做:
Candy.create(array, function (err) {
if (err) // ...
for (var i=1; i<arguments.length; ++i) {
var candy = arguments[i];
// do some stuff with candy
}
});
Run Code Online (Sandbox Code Playgroud)
使用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);
});
Run Code Online (Sandbox Code Playgroud)
从 Mongoose v5 开始,您可以使用insertMany
根据mongoose 站点,它比以下速度更快.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
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25704 次 |
| 最近记录: |