我的数据库中有以下架构:
{ name: 'AFG',
documents: [
{ name: 'doc1',
templates: [
{ name: 'templ1',
lastModified: <Date>},
...]
},
...]
}
我正在尝试查询名称为“templ1”的模板。如果我找到它,我必须将最后修改日期与另一个修改日期进行比较并更新该值。如果我没有找到它,我必须把它推入阵列。
我尝试使用以下查询执行此操作:
Country.findOne({name : countrySelected, documents : {$elemMatch: {name: documentSelected}}, 'documents.templates' : {$elemMatch: {name: templateSelected}}}, function(err, templateFound){...}
但是我收到以下错误:
MongoError: cannot use the part (documents of documents.templates) to traverse the element ({documents: [ { name: "Passport", templates: [] }, { name: "Visa", templates: [] }, { name: "Driver's Licence", templates: [] }, { name: "Id Card", templates: [] }, { name: "Other", templates: [] } ]})
有人知道我该怎么办?谢谢!
答案 0 :(得分:0)
您必须使用$in
运算符搜索数组。
Country.findOne({
name : countrySelected,
documents: {
$elemMatch: {
$and: [{
name: {
$in: documentSelected //<-- must be array like ['doc1']
}
}, {
'templates.name': {
$in: documentSelected //<-- must be array like ['tmpl1']
}
}]
}
}
}, function(err, templateFound){
//do something with err and templateFound
});
要更新LastModified日期,您需要在回调函数中更新它并保存文档。