由于MissingSchemaError,不会填充Mongoose .populate()

时间:2017-06-22 21:16:31

标签: node.js express mongoose

我正在尝试使用Mongoose中使用对象ID引用的用户信息填充users数组。

这是我的user.js模型:

var mongoose = require('mongoose');

var User = mongoose.Schema({
    conversations: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Conversations'
        }
    ],
    messages: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Messages'
        }
    ]
});

var User = module.exports = mongoose.model('Users', User);

module.exports.getUserByUsername = function(username, callback) {
    var query = {username: username};
    User.findOne(query, callback);
}

module.exports.getUserById = function(id, callback) {
    User.findById(id, callback);
}

我的conversation.js型号:

var mongoose = require('mongoose');

var Conversation = mongoose.Schema({
    created_at: Date,
    created_by_user_id: String,
    sent_to_user_id: String,
    messages: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Messages'
        }
    ],
    users: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'User'
        }
    ]

});

var Conversation = module.exports = mongoose.model('Conversations', Conversation);

我在我的users.js路线中使用它们是这样的:

var User = require('../models/user')
var Conversation = require('../models/conversation')

router.get('/member', ensureAuthenticated, function(req, res, next) {
  Conversation.find({ users: req.user._id }).populate('users').exec((err, conversations) => {
    // Code
  })
})

.populate('users')未执行。我收到此错误:MissingSchemaError: Schema hasn't been registered for model "User".有任何想法吗?

1 个答案:

答案 0 :(得分:2)

您在user.js中导出的​​模型名称为Users,并且您尝试在conversation.js中使用User引用它,这就是为什么它会给您错误。将User更改为Users,它应该可以正常工作