我正在尝试根据填充的子文档获取文档。
这是我的模特
// 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引用文档来抓住用户?
例如,查找具有Blog.tags
为“ {food”,“汽车”,“电影”和/或Blog.other
为[{...SomeObject}, {...SomeOtherObject}]
的Blog的用户
答案 0 :(得分:1)
查看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");
}