我知道也有与此类似的问题,但是对这些问题的答案并未得出正确的结果。
我想用猫鼬查找查询嵌套对象。这是我目前的设置:
reportRoutes.route('/:id').get(async (req, res) => {
try{
let id = req.params.id
let author = req.params.author
let regex = new RegExp( id, 'i')
const report = await Report.find({title: regex, 'player.player_name': "James Harden" })
.populate({path: 'like'})
.populate({
path: 'player',
populate: [{ path: 'team' },
{
path: 'team',
populate: {
path: 'league'
}
}
]
})
res.json(report)
} catch (e) {
res.status(500).send()
}
})
在邮递员中运行此命令时,会收到一个空白数组。
这是我正在使用的查询字符串的路由:localhost:4000/reports/harden
这是报表的架构:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
let Report = new Schema({
title: {
type: String
},
summary: {
type: String
},
analysis: {
type: String
},
source_title: {
type: String
},
source_link: {
type: String
},
author: {
type: String
},
like: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Like'
}],
player: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Player'
}
}, { timestamps: true })
module.exports = mongoose.model('Report', Report)
这是播放器的架构:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
let Player = new Schema({
player_name: {
type: String
},
player_position: {
type: String
},
team: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Team'
}
}, { timestamps: true })
module.exports = mongoose.model('Player', Player)
答案 0 :(得分:1)
由于您使用的是populate
,请尝试使用match
阶段:
reportRoutes.route('/:id').get(async (req, res) => {
try{
let id = req.params.id
let author = req.params.author
let regex = new RegExp( id, 'i')
const report = await Report.find({ title: regex })
.populate({path: 'like'})
.populate({
path: 'player',
match: { 'player_name': 'James Harden'}, // <-- match here
populate: [{ path: 'team' },
{
path: 'team',
populate: {
path: 'league'
}
}]
})
res.json(report)
} catch (e) {
res.status(500).send()
}
})
有关此文档,请参见here