gpt4 book ai didi

javascript - 无法 "skip" Mongoose 子文档

转载 作者:太空宇宙 更新时间:2023-11-03 22:36:02 27 4
gpt4 key购买 nike

我正在使用 Mongoose 和 Node ,我正在尝试对子文档中的数据进行分页。我可以限制子文档,但不能跳过它们。

我使用的版本是:

蒙戈3.0.0

Node 0.10.33

Mongoose 3.9.7

数据

[{ 
"name" : "Ranger Table",
"_id" : ObjectId("550234d3d06039d507d238d8"),
"body" : [
{
"name" : "Jason",
"colour" : "Red",
"animal" : "T-rex",
"_id" : ObjectId("550234d3d06039d507d238de")
},
{
"name" : "Billy",
"colour" : "Blue",
"animal" : "Triceratops",
"_id" : ObjectId("550234d3d06039d507d238dd")
},
{
"name" : "Zach",
"colour" : "Black",
"animal" : "Mastadon",
"_id" : ObjectId("550234d3d06039d507d238dc")

},
{
"name" : "Tommy",
"colour" : "Green",
"animal" : "Dragon"
"_id" : ObjectId("550234d3d06039d507d238d9")
}
]
},{
"name" : "Bot Table",
"_id" : ObjectId("5502d205184cd74033f64e6b"),
"body" : [
{
"name" : "Optimus",
"team" : "Autobots",
"class" : "Leader",
"_id" : ObjectId("550234d3d06039d507d238d9")
},
{
"name" : "Bumblebee",
"team" : "Autobots",
"class" : "Scout",
"_id" : ObjectId("550234d3d06039d507d238da")
},
{
"name" : "Astrotrain",
"team" : "Decepticons",
"class" : "Transport",
"_id" : ObjectId("550234d3d06039d507d238db")

}
]
}]

代码

var BodySchema = new Schema({random: String},{strict:false});

var FeedSchema = new Schema({
name: String,
body:[BodySchema]
});

var feed = mongoose.model('Feed', FeedSchema);

feed.find({_id:'550234d3d06039d507d238d8'})
.populate({
"path":"body",
"options":{
limit:2, //This works fine
skip:2 //This doesn't work
}
})
.exec(function(err, result){

if(err){return(res.send(500, err))}

res.send(result);
});

结果上面的代码确实将“body”子文档的数量限制为 2,但不跳过任何子文档。

上面的代码返回:

{ 
"name" : "Ranger Table",
"_id" : ObjectId("550234d3d06039d507d238d8"),
"body" : [
{
"name" : "Jason",
"colour" : "Red",
"animal" : "T-rex",
"_id" : ObjectId("550234d3d06039d507d238de")
},
{
"name" : "Billy",
"colour" : "Blue",
"animal" : "Triceratops",
"_id" : ObjectId("550234d3d06039d507d238dd")
}
]
}

但它应该返回这个:

{ 
"name" : "Ranger Table",
"_id" : ObjectId("550234d3d06039d507d238d8"),
"body" : [
{
"name" : "Zach",
"colour" : "Black",
"animal" : "Mastadon",
"_id" : ObjectId("550234d3d06039d507d238dc")

},
{
"name" : "Tommy",
"colour" : "Green",
"animal" : "Dragon"
"_id" : ObjectId("550234d3d06039d507d238d9")
}
]
}

最佳答案

我找到的解决方案是使用聚合并使用 $unwind 指定子文档的名称。

http://docs.mongodb.org/manual/reference/operator/aggregation/

feed.aggregate([
{'$match':{_id:id('550234d3d06039d507d238d8')}},
{'$unwind':'$body'},
{'$skip':2},
{'$limit':2},
], function(err, result){

if(err){return(res.send(500, err))}

res.send(result);

});

关于javascript - 无法 "skip" Mongoose 子文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29032727/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com