如何通过一次调用将一组对象推送到 mongoose 中的数组中? [英] How to push an array of objects into an array in mongoose with one call?
问题描述
我需要使用一次调用将多个值推送到 mongoose 中的一个数组中.我尝试使用较小的数组来执行此操作,但该数组已作为子数组插入.
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] }
我注意到的另一件事是数组中的类型(值)被指定为数字,那么严格"选项不会确保不插入数字以外的任何内容吗?在这种情况下,允许插入另一个数组.
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");
}
});
这篇关于如何通过一次调用将一组对象推送到 mongoose 中的数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!