【发布时间】:2020-06-18 11:53:36
【问题描述】:
我试图从同一个 json 对象响应中的两个集合中获取数据。 我正在尝试使用 $lookup 加入这两个集合,但它不起作用:
db.getCollection('profiles').aggregate( [
{
{
$match: {_id: ObjectId(userId) }
},
$lookup: {
from: "users",
localField: "user",
foreingField: "_id",
as: "user_data"
}
}
])
在配置文件模型中,用户声明如下:
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: [ true, 'A reference to a user must exist']
},
这是我可以在控制台中看到的调试查询:
Mongoose: users.aggregate([ { '$match': { _id: 5eec20720ff19056d079e953 } }, { '$lookup': { from: 'profile', localField: '_id', foreignField: 'user', as: 'profile_data' } }], {})
【问题讨论】:
-
英文标题:“在 JSON 对象上动态创建属性”用 SO 西班牙语发布。
-
db.user.aggregate([{ $unionWith: "Collection1" },{ $unionWith: "Collection2" }, ....])
-
对不起,我在用西班牙语思考,我该如何编辑它?谢谢
-
你的问题有点不清楚是
user的name和surname拐杖吗? -
您说的是
profile模型,但您写的是user。here: user: { type: Schema.Types.ObjectId, ref: 'User', required: [ true, 'A reference to a user must exist'] }。如果您可以放置模型的形状(甚至是部分),我会提供很大帮助。