猫鼬创建多个文档 [英] Mongoose create multiple documents

查看:67
本文介绍了猫鼬创建多个文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在最新版本的Mongoose中,您可以将多个文档传递给create方法,或者在我的情况下甚至可以传递一组文档.

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.

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?

推荐答案

您可以通过

You can access the variable list of parameters to your callback via arguments. So you could do something like:

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

    for (var i=1; i<arguments.length; ++i) {
        var candy = arguments[i];
        // do some stuff with candy
    }
});

这篇关于猫鼬创建多个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆