猫鼬populate()返回未定义

时间:2020-05-08 14:31:57

标签: node.js mongodb mongoose

我正在尝试与node.js,Express和MongoDB创建聊天。我有两种猫鼬模型:用于聊天室和消息。

房间型号:

const RoomSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
    },
    owner: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Users',
        required: true,
    },

    messages: {
        type: [mongoose.Schema.Types.ObjectId],
        ref: 'Messages',
        required: true,
    },
    users: {
        type: [mongoose.Schema.Types.ObjectId],
        ref: 'Users',
        required: true,
    },


});

const Room = mongoose.model('Rooms', RoomSchema);

消息模型:


const MessageSchema = new mongoose.Schema({
    text: {
        type: String,
        required: true,
    },
    sendBy: {
        type: String,
        required: true
    }

});

const Messages = mongoose.model('Messages', MessageSchema);

以及用于显示所有消息的功能

prepareMessages: function (name, callback) {
        rooms.findOne({
            name: name,
        }).populate('messages')
            .exec(function (err, room) {
                let result = '';
                if (!room) {
                    console.log("Chat does not exist");
                    throw err;
                }
                else {

                    room.messages.forEach(function (item, i, arr) {
                        result += '<dt>' + item.sendBy + '</dt>';
                        result += '<dd>' + item.text + '</dd>';
                    });
                }
                callback(result)
            });
    },

我为什么得到

TypeError: Cannot read property 'sendBy' of undefined

我尝试了.populate('rooms.messages').populate({path: 'rooms.messages', model:'Messages')和其他变体,但仍然无法使用。请帮帮我!

2 个答案:

答案 0 :(得分:0)

在“房间模式”中,您将消息定义为对象类型为ObjectId的对象,虽然它应该是元素数组,每个元素的类型都是ObjectId,消息应该是对象ID的数组,并且用户以及

const RoomSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
    },
    owner: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Users',
        required: true,
    },

    messages: [{ // note here messages is an array
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Messages',
        required: true,
    }],
    users: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Users',
        required: true,
    }],


});

const Room = mongoose.model('Rooms', RoomSchema);

希望有帮助

答案 1 :(得分:0)

  1. sendBy应该是ObjectId类型

const MessageSchema = new mongoose.Schema({ 文字:{ 类型:字符串, 必填:是, }, sendBy:{ 类型:mongoose.Schema.Types.ObjectId, 必填:true }

});

const Messages = mongoose.model('Messages',MessageSchema);

  1. ref应该小写。

    ref:“用户”,应更改为ref:“用户”

与其他所有ref相似