Reputation: 97
I'm trying to post the messages array to mongoose database, but it only saves the _id property instead the content and sender property too. What am I doing wrong?
Group Schema:
var GroupSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlenght: 1,
trim: true
},
messages: {
type: [{type: Schema.ObjectId, ref: 'Message'}]
},
_creator: {
type: mongoose.Schema.Types.ObjectId,
required: true
}
});
Message Schema:
var MessageSchema = new mongoose.Schema({
content: {
type: String,
required: true,
minlenght: 1,
trim: true
},
sender: {
type: String,
required: true
}
});
POST /rooms route without saving
const messages = [];
for (const m of req.body.messages) {
messages.push(new Message(m));
}
var group = new Group({
name: req.body.name,
_creator: req.user._id,
messages: messages
});
When I run GET I only get back the messages objectID values
Upvotes: 3
Views: 1664
Reputation: 18515
This is by design. You have a cross-reference between your GroupSchema
and your MessageSchema
via:
messages: {
type: [{type: Schema.ObjectId, ref: 'Message'}]
}
What this means is that GroupSchema/messages
would only contain the ObjectIds of the messages cross referenced with your Messages collection.
You need to use populate to get the actual documents loaded.
The ref option is what tells Mongoose which model to use during population.
Upvotes: 1