【发布时间】:2019-10-29 06:55:48
【问题描述】:
我正在为我的快递应用程序实现收藏/取消收藏功能,但我在如何计算帖子被收藏的总数方面遇到了问题。
假设我有这个食谱架构
RecipeSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
maxlength: 30
},
description: {
type: String,
default: ''
},
favoritesCount: {
type: Number,
default: 0
}
})
和用户架构
const UserSchema = new mongoose.Schema({
username: {
type: String,
minlength: 8,
required: true,
unique: true
},
fullname: {
type: String,
maxlength: 40,
minlength: 4,
required: true
},
password: {
type: String,
required: true,
minlength: 8
}
favorites: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Recipe'
}]
}, { timestamps: true });
现在假设我有这个用户文档, 如何计算每个用户文档的收藏夹数组中存在的 Recipe ID (5daef9a2761d4b1668214dbc) 总数?
[{
username: 'john123',
email: 'john@test.com',
favorites: ['5daef9a2761d4b1668214dbc']
}, {
username: 'jane75',
email: 'jane@test.com',
favorites: []
}, {
username: 'johnwick',
email: 'johnwick@test.com',
favorites: ['5daef9a2761d4b1668214dbc']
}]
// Should yield 2
我查找了答案,但找不到。我是 mongodb 和 nodejs 的新手,所以请多多包涵。我看到的一些答案与聚合有关。
到目前为止,我已经尝试过这段代码。但它只返回用户文档的数量。
const User = require('./User') // the User model
RecipeSchema.methods.updateFavoriteCount = function() {
return User.count({
favorites: {
$in: [this._id]
}
}).then((count) => {
this.favoritesCount = count;
return this.save();
});
};
【问题讨论】:
标签: node.js mongodb express mongoose