Reputation: 2137
I am building a messaging system in node.js,socket.io and mongoDB. I am well aware of node.js and socket.io but I am new to mongoDB. Here are my mongoose schema uptil now:
conversation_model.js:
const mongoose = require('mongoose');
const conversationSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: String,
created_at: {type: Date, default: Date.now}
});
module.exports = mongoose.model('Conversation', conversationSchema);
and in message_model.js I have:
const mongoose = require('mongoose');
const messageSchema = new mongoose.Schema({
message: String,
conversation_id: String,
user_id: Number
});
module.exports = mongoose.model('Message', messageSchema);
My conversations are created in separate express route and after sometimes when users add messages then I save new messages like this:
MessageModel.create(
{
conversation_id: data.conversation_id,
message: data.message,
user_id: data.user_id
}
).then((response) => {
callback(response);
}).catch(err => console.error(err));
The message is saved as well in it's relevant collection. But now I want to retrieve a conversation and all it's messages in on mongoose find operation.
I have read about mongoose populate and created reference of messages in conversation model as well but when I query then I don't get messages added in the conversation.
Here is my find call:
ConversationModel.findById(conversation_id).populate('messages').then(conversationDetail => {
console.log(conversationDetail);
}).catch(err => console.error(err));
And here is my updated conversation model to fetch messages along with conversation find operation:
const mongoose = require('mongoose');
const conversationSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: String,
created_at: {type: Date, default: Date.now},
messages :[{type: mongoose.Schema.Types.ObjectId, ref: 'Message' }]
});
module.exports = mongoose.model('Conversation', conversationSchema);
But it does not work. The conversation find operation always has message array to be empty even if the messages exist related to that conversation.
Also please tell me is it good idea to save conversation_id field in message model? Thanks
Upvotes: 0
Views: 445
Reputation: 22553
You are missing the back link on the your message model. So you really have no choice put to have the conversation_id in there if you want to use refs in that collection. Think of this as a being like a foreign key relation in SQL.
conversation_id: String,
should be:
conversation_id: {type: mongoose.Schema.Types.ObjectId, ref: "Conversation", index: true}
Upvotes: 1