Mongodb Mongoose:在.populate({match})中使用$or
我已经建立了这样一个数据库:Mongodb Mongoose:在.populate({match})中使用$or,mongodb,mongoose,mongoose-populate,Mongodb,Mongoose,Mongoose Populate,我已经建立了这样一个数据库: const listSchema = new mongoose.Schema({ name: { type: String, required: true, trim: true }, additionalInfo: { type: String, required: false }, author: { required: true,
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;
现在,我想做的是:我想选择所有具有特定作者的列表,然后接触VOC并通过translationGerman和translationForeignLanguage过滤这些VOC:我想在所有具有特定值的列表中选择所有VOC(让我们说“translationGerman”或“translationForeignLanguage”中的“apple”一词)“translationForeignLanguage”已存储。我尝试了以下代码:
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'});
}
})
router.get('/api/filteralwords/:wordname',auth,async(req,res)=>{
试一试{
//const words=wait Voc.find({$or:[{translationForeignLanguage:req.params.wordname},{translationGerman:req.params.wordname}]});
//控制台日志(文字);
//res.send(文字)
const lists=wait List.find({author:req.user.\u id});
设allVocs=[];
for(设i=0;i
当我尝试测试代码时,它会向我发送错误“意外令牌”。我是否使用了$or内部填充(匹配)错误。当我尝试重复此代码时,仅将“translationForeignLanguage:req.params.wordname”作为匹配参数,一切都很好,工作正常
谢谢你的帮助
Julia只要去掉
匹配
(围绕$或
语句)中多余的花括号,它就可以工作了:
lists[i]
.populate({
path: 'vocs',
match: {
$or: [
{ translationForeignLanguage: req.params.wordname },
{ translationGerman: req.params.wordname },
],
},
})
.execPopulate();
lists[i]
.populate({
path: 'vocs',
match: {
$or: [
{ translationForeignLanguage: req.params.wordname },
{ translationGerman: req.params.wordname },
],
},
})
.execPopulate();