I'm building an API for my chat application and I wrote the endpoint below to save new messages in MongoDB.
The messages themselves are an array.
Testing this endpoint with Postman returns the newly created message in the response but the message is not added to my array of messages.
router.post('/:id/messages', async (request, response) => {
const chatMessage = new Message({
type: request.body.type,
body: request.body.body,
author: request.body.author
});
try {
const newMessage = await chatMessage.save({ $push: { chatMessage } });
response.status(201).json(newMessage);
} catch (error) {
response.status(400).json({ message: error.message });
}
});
Here's my Mongoose schema for messages:
const mongoose = require('mongoose');
const messageSchema = new mongoose.Schema({
type: {
type: String
},
body: {
type: String
},
author: {
type: String
},
date: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('Message', messageSchema);
Any hints on what I've done wrong? Thank you so much! :-)
EDIT_ Mongo DB Sample
:iddoing over there, Also are you inserting intoMessagecollection or any other collection ? Plus where is the array in your schema ? Can you please give us sample of your docs from whatever collection you wanted to insert for better understanding..message :[]lies inside a document of some other collection ? (And message is an array of objects) ??Every document in my DB has a messages document inside--> what do you mean by this ? DB will have collections & collections will have documents !! So in which collection do you want an array of objects called message as you don't want message collection then messages should got into a document of a collection !!_idin this case