javascript - 聚合组合两个 ObjectAarray
问题描述
我想将评论的用户与 NodeJS 中的个人资料图片结合起来,以便在出现评论时显示个人资料图片。
我有以下代码:
Mission.aggregate([
{
$match: {
_id: ({ $in: [mongoose.Types.ObjectId(id)] })
}
},
{
$limit: 1
},
{
$unwind: {
"path": "$comments",
"preserveNullAndEmptyArrays": true
}
},
{
$lookup: {
"from": "users",
"localField": "comments.user",
"foreignField": "username",
"as": "user"
}
},
{
$unwind: {
"path": "$user",
"preserveNullAndEmptyArrays": true
}
},
{
$group: {
"_id": "$_id",
"comment": { "$push": "$comments" },
"user": { "$push": "$user.profilePicture" },
}
}
], ...)
任务模型如下所示:
creator: {
type: String,
required: true
},
text: {
type: String,
required: true,
minlength: 4,
maxlength: 100
},
comments: [{
user: {
type: String,
required: true
},
text: {
type: String,
required: true,
minLength: 2,
maxLength: 500
},
date: {
date: Date
}
}]
用户模型如下所示:
username: {
type: String,
required: true,
index: { unique: true },
minlength: 3,
maxlength: 16
},
password: {
type: String,
required: true,
minlength: 60,
maxlength: 60
},
email: {
type: String,
required: true,
validate: {
validator: function (v) {
return /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/.test(v);
},
message: '{VALUE} is not a valid email address!'
},
},
profilePicture: {
type: String
},
creationDate: {
type: Date,
},
api: {
apiKey: {
type: String
},
apiSecret: {
type: String
}
}
问题是:如何在同一个对象中获取评论和 profilePicture?
解决方案
试着写(愿这对你有用)
{
$group: {
"_id": "$_id",
"userInfo":{
$push: {
"comment": "$comments",
"user": "$user.profilePicture"
}
}
}
}
推荐阅读
- c++ - 排列简单算法时的不同程序集
- android - 颤动的椭圆形
- javascript - 类型错误:定位器无效
- android - 指定的 Gradle 发行版“https://services.gradle.org/distributions/gradle-4.6-all.zip”似乎不包含 Gradle 发行版
- javascript - 点击后HTML更改按钮名称
- git - Jenkins 管道从 windows jenkins 服务器推送 git 标签
- vuejs2 - bootstrap-vue:b-table 如何防止可选表在某些情况下选择更改
- jquery - 如何重置由 Api 响应通过 javascript 呈现的表单的值
- linux - 获取 tmux 中其他窗格的标准输入
- jenkins - 在 Jenkins 管道中添加 SVN 结帐时出现凭据错误