如何仅在文档内查询和填充子文档?

时间:2017-04-27 09:02:39

标签: node.js mongoose

我有一个如下集合, enter image description here

我想查询并仅填充具有fromUser userID'233232'的评论 现在我的助手类如下,

 queryaggregateWithProject: function (model, matchedCond, prjCond) {
            return new Promise(function (resolve, reject) {
                model.aggregate([
                    {$match: matchedCond},
                    {$project: prjCond}
                ], function (error, data) {
                    if (error)
                        reject(error);
                    resolve(data);
                });
            })
        }

我应该为matchCond和projCond传递什么?

模式

module.exports = function () {
    var model = null;
    var modelName = '_purchase';
    try {
        model = dbService.getModel(modelName);
    } catch (error) {     

        var userSchema = dbService.createEntityDef({
            userId: {
                type: String
            },            
            urlPicture: {
                type: String
            }
        });
        var reviewSchema = dbService.createEntityDef({
            fromUser: userSchema,
            toUser: userSchema,
            rating: {
                type: Number
            },
            comment: {
                type: String
            }


        })


        var purchaseSchema = {
            _id: {
                type: dbService.getPrimaryKeyType(),
                index: true
            },
            purchaseId: {
                type: String
            },          
            reviews: [reviewSchema]

        };
        model = dbService.createModel(modelName, purchaseSchema, {
            name: 'text'
        }, modelName);
    }

    return model;
};

1 个答案:

答案 0 :(得分:1)

您的匹配信息

{ fromUser.userid : "youruserid" }

您的项目

{ document: "$$ROOT" }

将返回包含所有属性的对象。