【问题标题】:getting count within a findOne of a mongoose schema array field在 mongoose 模式数组字段的 findOne 中获取计数
【发布时间】:2017-05-03 03:56:21
【问题描述】:

我想使用 Mongoose 返回有关用户的信息以填充他们的个人资料。我一直在使用 findOne 通过嵌入式文档和 .populate 填充他们的 cmets 列表以及基本配置文件信息。我想通过计算朋友数组中有多少对象来计算他们拥有的朋友数。

看起来聚合是其中之一,但我如何同时使用两者?还是有一种简单的方法可以在 findOne 查询中进行计数?

var UserSchema = new Schema({
  username:  String,
  comments       : [{ type: Schema.Types.ObjectId, ref: 'Comment' }],
  friends: [
					{ 
						id: { type: Schema.Types.ObjectId, ref: 'User' },
						permission: Number 
					}
  ]
})
  
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')
	.populate({
		path: 'current',
		model: 'Comment',
		select: 'comment author -_id date',
		populate: {
			path: 'author',
			model: 'User',
			select: 'username firstName lastName -_id'
		}
	})	
.exec(function(err, user) {
//
})
)}

【问题讨论】:

  • 为什么不使用 user.friends.length ?

标签: mongodb express mongoose mongoose-schema


【解决方案1】:

如果用户返回好友数组,为什么不只返回 user.friends.length 呢?

如果你只想数,就用这个

User.aggregate([
     {
        $match: { username: req.params.username }
     },
     {
        $unwind: "$comments"
     },
     {
        $lookup: {
           from: "Comment",
           localField: "comments",
           foreignField: "_id",
           as: "comments"
        }
     },
     { 
        "$group": {
            "_id": "$_id",
            "friends": { "$first": "$friends"},
            "comments": { "$push": "$comments" }
         }
     },
     {
        $project: {
            _id: 0, 
            count: {$size: '$friends'},
            comments: 1,
            username: 1
        }
     }
]).exec() ...

【讨论】:

  • 因为当我只需要计数时,如果它们有很多整数,我会返回一个巨大的数组。如果我已经将 findOne 与 .populate 一起用于嵌入文档怎么办?我可以使用聚合来做同样的事情吗?或者我可以把它们结合起来吗?
  • 好吧,您不能将填充方法与聚合一起使用。相反,您必须使用查找方法来获取 cmets 对象。我更新了我的答案。搜索查找、展开和分组文档:docs.mongodb.com/manual/reference/operator/aggregation/lookup
  • 另外,我看了你编辑的答案。看来您可能不需要聚合。只要您不填充朋友集合,它只会返回对象 ID 列表的数组,这是可以的。您可以返回该长度。如果您仍然不想返回对象 id 列表,则必须使用可能需要更多时间来构建的聚合,因为我无法测试您的集合,既不是视图也不是所有模式。
猜你喜欢
  • 2017-08-18
  • 2021-07-12
  • 1970-01-01
  • 2018-02-07
  • 2019-03-18
  • 2023-03-17
  • 1970-01-01
  • 2021-09-17
  • 1970-01-01
相关资源
最近更新 更多