在 Mongoose 中,如何生成一个值为另一个字段数组长度的新字段?

In Mongoose, how do you generate a new field with a value that is the length of another field's array?

我有一个包含用户集合的简单数据库。这是文档的样子:

{
   username: "Joe",
   age: 20,
   friends: ["u2", "u5", "u6", "u7", "u11"]
}

我想创建一个查询 return 类似于

{
   username: "Joe",
   age: 20,
   total_friends: 5,
   friends: ["u2", "u5", "u6"]
}

注意我只切分了前 3 个朋友,因为我不想在每个查询中 return 所有 个用户朋友。

如何在切片之前创建 total_friends 字段?

这是我目前的情况:

UserModel.findById( new Types.ObjectId(userId))
             // what goes here??
            .slice('friends', 3)
            .populate('friends')
            .exec((err, doc) => {...});

您可以使用聚合框架。试试这个:

db.userModel.aggregate([
    {
        $addFields: {
            total_friends: { $size: "$friends" },
            friends: { $slice: [ "$friends", 3 ] }
        } 
    }
])

由于 5 元素数组是流水线阶段的输入 $size will return 5 elements and $slice 将在 5 元素数组上运行前三个。