Arrays 如何将新值推送到Mongoose中的嵌套数组
我在用猫鼬。如何将新值推送到数组Arrays 如何将新值推送到Mongoose中的嵌套数组,arrays,mongodb,mongoose,push,Arrays,Mongodb,Mongoose,Push,我在用猫鼬。如何将新值推送到数组fixture2 这是我的收藏。我使用userHash来标识此文档 { "_id" : ObjectId("5d2548beb1696f1a2d87d647"), "userHash" : "5c4b52fc2dfce2489c932e8fcd636a10", "fixtures" : [ { "fixture1" : [ "vote1",
fixture2
这是我的收藏。我使用userHash
来标识此文档
{
"_id" : ObjectId("5d2548beb1696f1a2d87d647"),
"userHash" : "5c4b52fc2dfce2489c932e8fcd636a10",
"fixtures" : [
{
"fixture1" : [
"vote1",
"vote2"
],
"fixture2" : [
"vote1",
"vote2",
"vote3"
],
"fixture3" : [
"vote1"
]
}
],
"__v" : 0
}
fixture
可以包含任意数量的元素。在这种情况下,它只有3个
这是我的模型
var mongoose = require( 'mongoose' );
var votesSchema = mongoose.Schema({
userHash: String,
fixtures: [{}]
});
module.exports = mongoose.model('votes', votesSchema);
但是,我正在努力将值
vote4
推送到fixture2
。是否可以使用findOneAndUpdate
提交此操作?您可以使用$push
执行此操作
例如:
YourModel.findOneAndUpdate(condition, {$push: {"fixtures.0.fixture2": "vote4"}})
您可以使用下面的查询
update(
{ "fixtures.fixture2": { "$exists": true } },
{ "$push": { "fixtures.$.fixture2": "vote4" } }
)
可以使用“位置”操作符来实现这一点
另外,不要忘记在更新选项中使用{multi:true}
,以更新集合中的所有文档
试试这个:
Votes.update(
{ "fixtures.fixture2": { "$exists": true } },
{ "$push": { "fixtures.$.fixture2": "vote4" } },
{ multi : true}
)
但这只会更新第一个匹配的fixture2
要更新fixtures
数组中所有元素的fixture2
,您可能需要使用$[]
试试这个:
Votes.update(
{ "fixtures.fixture2": { "$exists": true } },
{ "$push": { "fixtures.$[].fixture2": "vote4" } },
{ multi : true}
)
有关详细信息,请阅读更多信息。是否要推送到fixtures数组所有元素的fixture2?谢谢您的回答。。。实际上,这是我正在测试的最后一个查询,因为我需要检查哪些用户正在投票……```````devots.findOneAndUpdate({userHash:hash,'fixtures.fixture3':{$exists:true}},{$push:{“fixtures.$.fixture3:'vote11'}}})``但是,它仅在fixtures.fixture3
数组存在时才起作用。我想我需要做一些以前的验证,以验证数组是否存在。。。如果没有,我需要在尝试推送数据之前创建它。谢谢