node.js - 如何根据参考填充的子文档过滤 mongodb 上的文档?
问题描述
我正在尝试根据填充的子文档来获取文档。
这是我的模型
// User model
var UserSchema = new mongoose.Schema({
username: {type: String, required: true, trim: true},
firstName: {type: String, required: true, lowercase: true},
lastName: {type: String, required: true, lowercase: true},
phone: {type: String, required: false},
email: {type: String, required: true},
password: {type: String, required: true},
blogs: {type: mongoose.Schema.Types.ObjectId, ref: 'Blogs'}
}, {timestamps: true});
// Blog Model
var BlogSchema = new mongoose.Schema({
description: String,
tags: [String],
other: [Object],
}, {timestamps: true});
这就是我抓取文件的方式
fetchAllByFilter: async function(req, res) {
try {
let result = await Users.find({}).populate('blog');
return res.status(200).send(result);
} catch (err) {
return res.status(200).send({error: err});
}
},
现在我的主要问题是,我将如何根据用户的博客引用文档来获取用户?
例如,查找具有Blog.tags
“食物”、“汽车”、“电影”和/Blog.other
或[{...SomeObject}, {...SomeOtherObject}]
解决方案
查看 mongo docs match an array,您可以制作一个有点像这样的实用函数......
async function findByTag(tag) {
const blogIds = await Blog.find({ tags: tag }).select("_id");
const users = await User.find({
blogs: { $in: blogIds.map((blog) => blog._id) }
}).populate("blog");
}
推荐阅读
- three.js - Three.js - 将带有 TextGeometry 的场景导出到 OBJ/GLTF 然后由 OBJ/GLTF Loader 加载
- javascript - 为什么我托管在 heroku 上的不和谐机器人随机关闭?
- kubernetes - 如何找到 kubectl 支持的给定资源类型的字段选择器列表?
- java - 如何在java中传递aws iot x.509证书路径
- php - Ajax 请求在页面加载然后刷新时不起作用,但在单击指向同一页面的链接后会起作用
- reactjs - 如何仅在 firebaseAuthIsReady 时返回组件
- c++ - 如何从右到左展开参数包
- computer-vision - 从 imagenet 下载数据
- python - AttributeError:“str”对象没有属性“detect_intent”
- swift - 我正在做一个发布请求,我想在其中输入一个问题,并通过发布请求获得最常见的答案