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
});
JSON data in postman
When I run GET I only get back the messages objectID values
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With