【发布时间】:2019-10-12 01:58:50
【问题描述】:
我知道有与此类似的问题,但这些问题的答案并没有产生正确的结果。
我想用 mongoose find 查询一个嵌套对象。这是我目前的设置:
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)
【问题讨论】:
-
当您只搜索
title而没有嵌套播放器等时会发生什么。那么您得到任何结果吗?搜索没有正则表达式,只搜索标题,看看是否所有的填充都有效。还可以尝试删除所有populates 并查看是否使用 regEx 等获得结果。 -
@akrion 当我使用正则表达式搜索
title时,我收到了正确的结果,并且所有填充都有效。没有正则表达式,我收到一个空数组。尝试使用正则表达式删除填充,并收到一个空数组。每当我收到一个空数组时,邮递员都会告诉我我有一个200 OK。感谢您的帮助,我很坚持这个。