简体   繁体   中英

Mongoose populate method only storing one Object

I'm trying to access the array of Message Models that is stored in my Conversation Model. However, when I use the populate method to try to store the Message models as an array, only the first Message is showing up.

socket.on('connected', function (data) {
      //load all messages
      const filter = { roomId: data.roomid };
      (async () => {
        console.log('searching for Schema');
        let conversation = await Conversation.findOne(filter)
          .populate('messages')
          .exec(function (err, message) {
            if (err) console.log('no schema found');
            var array = message.messages;
            console.log(array);
            // printing only first Message
          });
      })();
    });

Conversation Schema

const ConversationSchema = new mongoose.Schema(
    {
        roomId: {
            type: String,
            required: true
        },
        messages: {
            type:  mongoose.Schema.Types.ObjectId, ref: 'Message' 
        }
    },
    {
        timestamps: true
    }
);

populate method not store message as an array.Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s). Refer this for more detail

To solve your problem modify declaration of messages field in Conversation Schema

messages: [{
            type:  mongoose.Schema.Types.ObjectId, ref: 'Message' 
        }]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM