在填充的集合中,通过request.params ..在findOne中聚合$ match不起作用。猫鼬nodejs

时间:2015-01-24 21:56:48

标签: node.js mongodb mongoose

   'use strict';

var mongoose = require('mongoose'),
    ItemSchema = null;

module.exports = mongoose.model('Item', {
    name:  {type: String, required: true},
    comments: [{type: mongoose.Schema.ObjectId, ref: 'Comment'}],
    rating : {type: Number}
});

'use strict';

var mongoose = require('mongoose');

module.exports = mongoose.model('Comment', {
    ItemId:   {type: mongoose.Schema.ObjectId, ref: 'Item'},
    userId:   {type: mongoose.Schema.ObjectId, ref: 'User'},
    text:     {type: String, required: true},
    createdAt: {type: Date,  required: true, default: Date.now},
    rating  : {type: Number, required: true},
    votes:     {type: Number, default: 0}
});

var Item = mongoose.model('Item', ItemSchema);
module.exports = Item;

模式在上面..匹配不起作用,我认为它应该如何。真的很难模仿这些连接..我只是想在评论中回复一个带有评论的项目及其给出的平均评分。

 Item.findOne({_id : request.params.itemId} , 'comments',function(err, item){
                Comment.aggregate([
                    {$match: {_id: {$in: item.comments}}},
                    {$group: {_id: '$itemId', avgRating: {$avg: '$rating'}}}], function(err, result){

                    reply(result);
                });
            });
        }

如果我拿出比赛,它将返回所有avgRating项目...我在$ match中实现了错误。


这是我尝试删除findOne时所做的:

 Comment.aggregate([
    {$match: {itemId : request.params.itemId}},
            {$group: {_id: '$itemId', avgRating: {$avg: '$rating'}}}], function(err, result){

            reply(result);

            console.log('BBBBBB', result);
        });

不确定这是否是您删除findOne的意思,但这也无效.. request.params返回正确的ID。它绝对是评论中的有效字段,数据库中有一个带有此匹配ID的评论...

0 个答案:

没有答案
相关问题