我试图通过 id 在数据库中获取特定的测验:
static getQuiz(db, id, cb){ //db is database connection, id is quiz id, cb is just callback
db.find({ _id : "8RA4Rey50eqKFlWK"}, {"quiz" : { $elemMatch : { _id : id}}}, function(err, Doc){
if(cb){
cb(err,Doc);
console.log(Doc); //only return _id : "8RA4Rey50eqKFlWK"
}
})
}
JSON数据库:
{
"_id":"8RA4Rey50eqKFlWK",
"quiz":[
{
"_id":"1b944055-2b15-4838-7e7a-beef4c9a5a62",
"title":"test",
"description":""
},
{
"_id":"7dc53529-206c-6003-1d3c-133264d7ad81",
"title":"aaaa",
"description":""
},
{
"_id":"db3c788f-56b3-f9c8-8a25-affb2981e12f",
"title":"lala",
"description":""
},
{
"_id":"20388c1f-1a00-4f7b-3d25-9db56247a6bf",
"title":"asdasd",
"description":""
}
]
}
上面的代码不起作用,已经测试过:
db.find({ _id : "8RA4Rey50eqKFlWK"}, {"quiz" : { $elemMatch : { title : "test"}}})
但结果仍然只是 root id => _id :“8RA4Rey50eqKFlWK”。
当按 ID“1b944055-2b15-4838-7e7a-beef4c9a5a62”搜索测验时,我期望结果应该是:
{
"_id":"8RA4Rey50eqKFlWK",
"quiz":[
{
"_id":"1b944055-2b15-4838-7e7a-beef4c9a5a62",
"title":"test",
"description":""
},
]
}
有什么解决办法吗?我实际上使用的是 NeDB https://github.com/louischatriot/nedb,它的语法与 MongoDB 相同。谢谢
编辑:我使用 mongodb 控制台尝试了我的代码,它工作得很好!也许那只是 NeDB 错误?