如何转换authorid关联postid提取作者信息存入authorDocument数组及代码排查
问题定位
- 语法错误:代码中的
"是HTML转义后的双引号符号,不属于JavaScript合法语法,直接运行会抛出语法错误,需要先替换为标准的双引号"。 - 关联字段类型不匹配:MongoDB的
$lookup要求关联的两个字段类型完全一致才能匹配成功。你的代码已经通过$addFields将字符串格式的作者ID转换为ObjectId类型存储在authorId字段,但后续$lookup的localField仍使用了原字符串类型的author字段,和users集合的_id(默认是ObjectId类型)类型不匹配,导致关联失败拿不到作者数据。
修正后代码
let posts = await postsCollection.aggregate([ {$match: {_id: new ObjectID(id)}}, {$addFields: {authorId: { $toObjectId: "$author"}}}, // 替换localField为转换后的ObjectId类型字段即可 {$lookup: {from: "users", localField: "authorId", foreignField: "_id", as: "authorDocument"}} ]).toArray()
补充优化
如果你的posts集合中author字段本身已经是ObjectId类型,可以直接省略$addFields阶段简化代码:
let posts = await postsCollection.aggregate([ {$match: {_id: new ObjectID(id)}}, {$lookup: {from: "users", localField: "author", foreignField: "_id", as: "authorDocument"}} ]).toArray()
如果单篇帖子只有一个作者,还可以在聚合最后增加一步把返回的数组类型authorDocument转成单个对象,更方便后续调用:
let posts = await postsCollection.aggregate([ {$match: {_id: new ObjectID(id)}}, {$addFields: {authorId: { $toObjectId: "$author"}}}, {$lookup: {from: "users", localField: "authorId", foreignField: "_id", as: "authorDocument"}}, {$addFields: {authorDocument: {$first: "$authorDocument"}}} ]).toArray()
内容的提问来源于stack exchange,提问作者Bivishan Sapkota
相关产品推荐
相关产品推荐

