如何通过一次调用将对象数组推入猫鼬数组中? [英] How to push an array of objects into an array in mongoose with one call?

查看:86
本文介绍了如何通过一次调用将对象数组推入猫鼬数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用一个调用将多个值以猫鼬的形式推入数组.我尝试使用较小的数组来执行此操作,但是该数组将作为子数组插入.

I need to push multiple values into an array in mongoose using one call. I tried doing it using a smaller array but the array is getting inserted as a sub-array.

var kittySchema = new mongoose.Schema({
        name: String,
        values: [Number]
});

var Kitten = db.model('Kitten', kittySchema);
Kitten.update({name: 'fluffy'},{$push: {values:[2,3]}},{upsert:true},function(err){
        if(err){
                console.log(err);
        }else{
                console.log("Successfully added");
        }
});

调用上述代码三次的结果将得到以下结果:

The result of the calling the above code thrice gives the below result:

{ "_id" : ObjectId("502b0e807809d79e84403606"), "name" : "fluffy", "values" : [ [ 2, 3 ], [ 2, 3 ], [ 2, 3 ] ] }

我想要的是这样的

{ "_id" : ObjectId("502b0e807809d79e84403606"), "name" : "fluffy", "values" : [ 2, 3 ,2 ,3, 2, 3] }

我注意到的另一件事是将数组(值)中的类型指定为Number,那么'strict'选项是否可以确保未插入Numbers以外的任何内容?在这种情况下,允许插入另一个数组.

Another thing I noticed was that the type in the array (values) is specified as Number, then wouldnt the 'strict' option ensure that anything other than Numbers are not inserted ? In this case another array is being allowed to be inserted.

推荐答案

(2014年12月更新)自MongoDB2.4起,您应该使用:

(Dec-2014 update) Since MongoDB2.4 you should use:

Kitten.update({name: 'fluffy'}, {$push: {values: {$each: [2,3]}}}, {upsert:true}, function(err){
        if(err){
                console.log(err);
        }else{
                console.log("Successfully added");
        }
});

这篇关于如何通过一次调用将对象数组推入猫鼬数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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