Mongodb 什么';这是在mongoose/mongo中管理大型ObjectID数组的最佳方法
在这种情况下:Mongodb 什么';这是在mongoose/mongo中管理大型ObjectID数组的最佳方法,mongodb,mongoose,pagination,mongoose-schema,mongoose-populate,Mongodb,Mongoose,Pagination,Mongoose Schema,Mongoose Populate,在这种情况下: const PostSchema = new mongoose.Schema({ "content": { type: String, required: true }, "user": { type: mongoose.Schema.Types.ObjectId, required: true, ref: "User"
const PostSchema = new mongoose.Schema({
"content": {
type: String,
required: true
},
"user": {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: "User"
},
"created": {
type: Date,
default: Date.now()
},
"comments": [{
type: mongoose.Schema.Types.ObjectID,
ref: 'Comment'
}]
})
我希望一次能够获得10条评论,但我认为如果不每次都获得所有评论,就无法做到这一点。您可以使用加入集合并限制为10条。下面是一个例子,为了便于理解,我使用字符串表示\u id
$lookup
-有两种查找,我在这里使用了不相关查找,您可以在加入集合时进行并行聚合$match
帮助有条件地连接文档<使用不相关查找时,必须在$match
中使用code>$expr
<代码>$limit
帮助限制文档。如果需要,可以添加更多的阶段以在管道内执行聚合
这是剧本
db.PostSchema.aggregate([
{
"$lookup": {
"from": "Comment",
let: {
cId: "$comments"
},
"pipeline": [
{
$match: {
$expr: {
_id: {
in: [
"$$cId"
]
}
}
}
},
{
$limit: 10
}
],
"as": "comments"
}
}
])
工作答案对你有帮助吗?