在MEAN.JS中的不同模块中填充引用模型的数据

时间:2017-02-01 11:15:44

标签: angularjs node.js mongoose meanjs

我是MEAN堆栈的新手,我正在为我的项目使用MEAN.js(版本0.4.2)生成器。

我正在使用默认用户模块并创建了一个新模块' Topics'使用模块生成器。我有一个基于角色的基本登录系统,使用用户模块,用户可以在其中注册并查看/编辑他们的个人资料。在个人资料中,有一个名为' Topics'的主题模块的猫鼬模型的参考。

topic.server.model.js看起来像这样(这是主题的架构):

//Topic Schema
var TopicSchema = new Schema({
  .......
  user: {
    type: Schema.ObjectId,
    ref: 'User'
  }
});
mongoose.model('Topic', TopicSchema);

此模型中的内容可以访问用户模型中的数据。但是当我从用户模块引用它们时,我无法从主题模型中获取要显示的项目。

我的用户模型在架构中有这个:

var UserSchema = new Schema({
    ......
    interest: [{
        type: Schema.Types.ObjectId,
        ref: 'Topic'
    }],
    skills: [{
        type: Schema.Types.ObjectId,
        ref: 'Topic'
    }]
});
mongoose.model('User', UserSchema);

我正在尝试使用以下中间件填充主题中的数据:

exports.userByID = function (req, res, next, id) {
    if (!mongoose.Types.ObjectId.isValid(id)) {
        return res.status(400).send({
            message: 'User is invalid'
        });
    }
    User.findById(id, '-salt -password').populate('interest', 'name').populate('skills', 'name').exec(function (err, user) {
        if (err) {
            return next(err);
        } else if (!user) {
            return next(new Error('Failed to load user ' + id));
        }

        req.model = user;
        next();
    });
};

我需要一些指导,告诉我如何在前端显示数据,例如{{user.interest.name}}。

修改 在users.profile.server.controller中,没有从这里创建json:

exports.me = function (req, res, next) {
    var id = req.user._id;
    User.findOne({
        _id: id
    }).populate('interest', 'name').populate('skills', 'name').exec(function(err, userData) {
        if (err) return next(err);
        if (!userData) return next(new Error('Failed to load User ' + id));
        res.json(userData || null);
        next();
    });
};

在终端中收到以下错误:

GET /api/users/me 400 22.173 ms - -
Error: Can't set headers after they are sent.

0 个答案:

没有答案