Sails-Mongo - 在查询时从DB检索所有填充的数据

时间:2014-11-18 14:48:10

标签: mongodb associations sails.js waterline

我是Sails的新手。我有两个模型User.js和Project.js。 ProjectMember.js是链接两个模型的模型。 user.js的

module.exports = {

attributes: {
    userName: {
        type: 'string',
        unique: true
    },
    email: {
        type: 'email',
        required: true,
        unique: true
    },
    company: {
        type: 'string',
    },
    password: {
        type: 'String',
        required: true
    },
    passwordSalt: {
        type: 'String',
        required: true
    },
    deletedAt: {
        type: 'datetime',
        defaultsTo: null
    },
    projects: {
        collection: 'ProjectMember',
        via: 'user'
    }
  }
}

Project.js

module.exports = {

attributes: {

    name: {
        type: 'string',
        required: true,
        unique: true
    },
    description: {
        type: 'string'
    },
    company: {
        type: 'string',
        required: true
    },
    members: {
        collection: 'ProjectMember',
        via: 'project',
        dominant: true
    }
 }
}

ProjectMember.js

module.exports = {

attributes: {

    project: {
        model: 'Project'
    },
    user: {
        model: 'User'
    },
    projectRole: {
        model: 'ProjectRole'
    },
    deletedAt: {
        type: 'datetime',
        defaultsTo: null
    }
 }
}

我想从Project模型中检索数据,以便从其他模型中检索关联的模型/集合。有没有什么方法可以做到这一点,除了通过这样的所有模型:

        Project.find({
            id: projectID
        }).populate('members').exec(function (err, results) {
            async.each(results, function (result, error) {
                if (err) {
                    retObj.type = "failure";
                    retObj.message = "Error in getting user list";
                    callback(retObj);
                } else {
                    var ids = [];
                    for (var i = 0; i < result.members.length; i++) {
                        User.findOne({
                            id: result.members[i].user
                        }, function (err, resp) {
                            var userObject = new Object();
                            userObject.userID = resp.id;
                            if (err) {
                                retObj.type = "failure";
                                retObj.message = "Error in getting user list";
                                callback(retObj);
                            } else {
                                userObject.company = resp.company;
                                userObject.email = resp.email;
                                userObject.userName = resp.userName;
                                ids.push(userObject);
                                if (ids.length == result.members.length) {
                                    callback(ids);
                                }
                            }
                        });
                    }
                }
            });
        });

提前致谢。

0 个答案:

没有答案