要按嵌套引用筛选Mongoose,可以使用populate方法来填充引用字段。下面是一个包含代码示例的解决方法:
const mongoose = require('mongoose');
// 创建Comment模型
const commentSchema = mongoose.Schema({
text: String
});
const Comment = mongoose.model('Comment', commentSchema);
// 创建Post模型
const postSchema = mongoose.Schema({
title: String,
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
});
const Post = mongoose.model('Post', postSchema);
// 创建User模型
const userSchema = mongoose.Schema({
name: String,
posts: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Post' }]
});
const User = mongoose.model('User', userSchema);
User.findOne({ name: 'John' })
.populate({
path: 'posts',
populate: {
path: 'comments',
model: 'Comment'
}
})
.exec((err, user) => {
if (err) {
console.error(err);
return;
}
console.log(user);
});
在上面的代码中,我们首先通过调用findOne方法找到名为John的用户。然后,在populate方法中,我们指定了要填充的字段路径('posts'),以及要填充的嵌套字段路径('comments')。最后,我们使用exec方法执行查询,并在回调函数中打印用户对象。
这样,我们就可以按嵌套引用筛选Mongoose了。