我需要使用mongoose和mongodb在数组字段中搜索特定的ID。 我正在使用下一个代码,但结果总是一个空数组:
我做错了什么?
//模型
const mongoose=require('mongoose');
const ObjectId=mongoose.Types.ObjectId;
const modelosAnamneseSchema = new mongoose.Schema({
nome:{type:String, unique:true},
perguntasAtivas:[{type:mongoose.Schema.Types.ObjectId,ref:'Perguntadeanamnese'}],
});
// pergunta de anamnese model
const mongoose=require('mongoose');
const perguntasAnamneseSchema = new mongoose.Schema({
nome:{type:String, unique:true},
tipopergunta:{type:mongoose.Schema.Types.ObjectId, ref:'TipoPerguntaAnamnese'},
ativo:{type:Boolean},
temObservacao:{type:Boolean},
observacao:{type:String},
created_at:{type:Date,default:Date.now},
altered_at:{type:Date,default:Date.now}
});
module.exports=mongoose.model('Perguntadeanamnese', perguntasAnamneseSchema,'perguntasdeanamnese' );
//数据样本:
{'name':'test',
'perguntasAtivas':[
{_id: "5915bec7813317eaabd9897e", id: 2, nome: "Diabetes"},
{_id: "5915bec7813317eaabd98981", id: 5, nome: "Remédio de uso contínuo"},
{_id: "5915bec7813317eaabd9897d", id: 1, nome: "Alergias"},
{_id: "5915bec7813317eaabd98984", id: 8, nome: "Etilismo"}
]
//查询id =“5915bec7813317eaabd9897d”
const query={'perguntasAtivas._id': new ObjectId(req.params.id)};
ModeloAnamnese.find(query)
.exec( (err,data) => {
callback(err,data,res)
})
此处,查询返回空数组