gpt4 book ai didi

node.js - Mongoose – 如何限制 populate() 级别的深度?

转载 作者:太空宇宙 更新时间:2023-11-03 23:44:00 25 4
gpt4 key购买 nike

我有两个架构:

var categorySchema = mongoose.Schema({
title: String,
blogs: [{ type: ObjectId, ref: 'Blog' }]
})

var blogSchema = mongoose.Schema({
title: String,
description: String,
category: [{ type: ObjectId, ref: 'Category' }],
created: {type: Number, default: new Date().getTime()}
})

var Category = mongoose.model('Category', categorySchema)
var Blog = mongoose.model('Blog', blogSchema)

它们是交叉引用的:

  1. Blog 对象包含一个 Category 对象 (refs) 数组,以便能够获取与此博客相关的所有类别。
  2. Category 对象包含一个 Blog 对象(refs)数组,以便能够获取该类别的所有博客。

问题是当我尝试获取某个博客时。我需要填充类别数组以获取其标题:

Blog
.findOne({_id: _._id})
.populate('category')
.exec(function (err, __) {
callback(err, __);
})

我明白了...

{ title: 'My Blog',
description: 'description',,
_id: 51cb6bd845ba145e02000001,
__v: 0,
created: 1372285906662,
category:
[ { __v: 0,
_id: 51cb5ed6fd63867905000002,
priority: 3,
title: 'Music',
blogs: [Object] } ],
}

是的,我得到了类别标题,但我也在博客中得到了一些对象 - 它们也被填充了。但是博客对象可能包含许多子对象(帖子)以及我们所记得的类别字段。那么,类别字段中的所有对象都将递归填充,并且由于我在博客和类别之间有交叉链接,它将在循环中填充?

如何限制人口数量?我不想填充 Blog/category[n]/blogs: [],只填充直接的 category 字段,例如 title。谢谢。

最佳答案

来自mongoose docs :

It is debatable that we really want two sets of pointers as they may get out of sync. Instead we could skip populating and directly find() the stories we are interested in.

我会删除类别架构中博客的引用,只查询您感兴趣的文档。

“博客对象包含一个类别对象(refs)数组,以便能够获取与此博客相关的所有类别”:

Blog.findOne({_id: blogId})
.populate('category')
.exec(function (err, blog) {
callback(err, blog);
//blog.category is the array you want
})

“类别对象包含博客对象(refs)数组,以便能够获取该类别的所有博客”:

Blog.find({category: catId}) 
.exec(function (err, blogs) {
callback(err, blogs);
})

这是 $all query 的简化语法实际上在类别数组中搜索指定的 id。

关于node.js - Mongoose – 如何限制 populate() 级别的深度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17331682/

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