我需要查询一个嵌入的文档,但它返回空数组。我正在使用 mongoose、apollo 服务器和 graphQL。
我需要的是获取所有包含名为 parent 过滤的字段的文档,其中包含“name”字段。
这是模型:
const elfoSchema = new Schema
(
{
name:
{
type:String,unique:true
},parent:
{
type: Schema.ObjectId,ref:'Elfo'
},}
)
这是 graphql 类型:
type Elfo
{
id:ID
name:String
parent:Elfo
}
这是端点:
async function newElfo(name,parent)
{
const newElfo = new Elfo()
newElfo.name = name
if(parent)
{
newElfo.parent = parent
}
const storedElfo = await newElfo.save()
await storedElfo.populate('parent').execPopulate()
try {
if(storedElfo)
{
return storedElfo
}
} catch (error) {
throw new Error(error.message)
}
}
async function getElfoChildren(elfo)
{
const storedElfo = await Elfo.findById(elfo)
try {
if(!storedElfo) throw new Error('elfo not exist')
const elfoChildren = await Elfo.find({'parent.name':storedElfo.name}).populate('parent')
try {
if(elfoChildren)
{
return elfoChildren
}
} catch (error) {
throw new Error(error.message)
}
} catch (error) {
throw new Error(error.message)
}
}
但结果是这样的:
{
"data": {
"getElfoChildren": []
}
}
但是通过这个查询,我得到了所有结果:
const elfoChildren = await Elfo.find({'parent':storedElfo._id}).populate('parent')
结果:
{
"data": {
"getElfoChildren": [
{
"id": "6106c57fb080f1080e60b584","name": "elfo3","parent": {
"id": "6106c569b080f1080e60b583","name": "elfo2"
}
},{
"id": "6106c586b080f1080e60b585","name": "elfo4",{
"id": "6106c58ab080f1080e60b586","name": "elfo5",{
"id": "6106c58eb080f1080e60b587","name": "elfo6","name": "elfo2"
}
}
]
}
}
有人可以帮我吗?