【发布时间】:2019-10-14 07:45:44
【问题描述】:
我已经建立了一个这样的数据库:
const listSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
additionalInfo: {
type: String,
required: false
},
author: {
required: true,
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
})
listSchema.virtual('vocs', {
ref: 'Voc',
localField: '_id',
foreignField: 'list'
})
var List = mongoose.model('List', listSchema);
module.exports = List;
const vocSchema = new mongoose.Schema({
foreignLanguage: {
type: String,
required: true,
trim: true
},
translationGerman: {
type: String,
required: true,
trim: true
},
translationForeignLanguage: {
type: String,
required: true
},
difficulty: {
type: Number,
required: true
},
list: {
required: true,
type: mongoose.Schema.Types.ObjectId,
ref: 'List'
}
})
var Voc = mongoose.model('Voc', vocSchema);
module.exports = Voc;
现在,我想要做的是:我想选择具有特定作者的所有列表,然后联系 vocs 并通过 translationGerman 和 translationForeignLanguage 过滤这些 vocs:我想选择所有列表中的所有 vocs有一个特定的值(假设存储“translationGerman”或“translationForeignLanguage”中的“apple”一词。我尝试了以下代码:
router.get('/api/filterAllWords/:wordname', auth, async (req, res) => {
try {
// const words = await Voc.find({$or:[{translationForeignLanguage: req.params.wordname},{translationGerman: req.params.wordname}]});
// console.log(words);
// res.send(words)
const lists = await List.find({author: req.user._id});
let allVocs = [];
for (let i = 0; i < lists.length; i++) {
const singleListVocs = await lists[i].populate(
{path: "vocs",
match: {
{$or:[{translationForeignLanguage: req.params.wordname},{translationGerman: req.params.wordname}]}
}}).execPopulate();
for(let i = 0; i < singleListVocs.vocs.length; i++) {
allVocs.push(singleListVocs.vocs[i])
}
}
res.send(allVocs)
}
catch {
res.status(404).send({status: 'No vocs found'});
}
})
当我尝试测试代码时,它会向我发送错误“Unexpected token”。我是否使用了 $or 里面的 populate(match) 错误。当我尝试重复此代码时,只需将“translationForeignLanguage: req.params.wordname”作为匹配参数,一切都很好,并且运行良好!
感谢您的帮助!
朱莉娅
【问题讨论】:
标签: mongodb mongoose mongoose-populate