我想使用Mongoose來返回有關用戶的信息以填充其配置文件。我一直使用findOne通過嵌入式文檔和.populate填充他們的評論列表以及基本的配置文件信息。我想通過計算好友陣列中有多少個對象來計算他們所擁有的朋友的數量。在貓鼬模式數組字段的findOne中計數
它看起來像聚合是這樣做的,但我怎麼能使用兩者?或者是否有一個簡單的方法在findOne查詢中進行計數?
var UserSchema = new Schema({
username: String,
comments : [{ type: Schema.Types.ObjectId, ref: 'Comment' }],
friends: [
\t \t \t \t \t {
\t \t \t \t \t \t id: { type: Schema.Types.ObjectId, ref: 'User' },
\t \t \t \t \t \t permission: Number
\t \t \t \t \t }
]
})
var User = mongoose.model('User', UserSchema);
var Comment = mongoose.model('Comment', CommentSchema);
app.get('/profile/:username', function(req, res) {
User
.findOne({ username: req.params.username }, 'username friends -_id')
\t .populate({
\t \t path: 'current',
\t \t model: 'Comment',
\t \t select: 'comment author -_id date',
\t \t populate: {
\t \t \t path: 'author',
\t \t \t model: 'User',
\t \t \t select: 'username firstName lastName -_id'
\t \t }
\t }) \t
.exec(function(err, user) {
//
})
)}
爲什麼不使用user.friends.length? –