您好,我有一个如下所示的 Mongoose 模式,
const followingFollowersSchema = mongoose.Schema({
follower: {
type: mongoose.Schema.ObjectId,
ref: 'User'
},
following: {
type: mongoose.Schema.ObjectId,
ref: 'User'
},
});
我在调用时创建了一个路由,它过滤当前登录用户关注的所有用户并显示以下输出,{
"status": "success",
"results": 1,
"data": {
"following": [
{
"_id": "5ef4cd0205070d87156e19da",
"following": {
"_id": "5eeb92d69fceed6d91ad5743",
"name": "X Y"
}
}
]
}
}
但我想显示这样的输出,{
"status": "success",
"results": 1,
"data": {
"following": [
{
"_id": "5eeb92d69fceed6d91ad5743",
"name": "X Y"
}
]
}
}
我怎样才能做到这一点?任何帮助,将不胜感激。
最佳答案
您可以使用 $addFields替换现有字段和 $map转换内部数组:
let result = Model.aggregate([
{
$addFields: {
"data.following": {
$map: {
input: "$data.following",
in: "$$this.following"
}
}
}
}
])
Mongo Playground
关于node.js - 如何在 Mongoose 中将对象字段作为数组获取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62596911/