I have a function in node js that will find all the messages inside mongodb collection that I want to modify the value of the specific key before passing to res.json.
Collection
I want to modify the seen to be true before sending this to front end.
Solution I tried
export const getMessage = async (req, res) => {
try {
const message = await messageModel
.find({
conversationId: req.params.messageId,
})
.populate('senderId');
const newMessages = message.map((mess) => {
return { ...mess, seen: true };
});
console.log(newMessages);
res.status(200).json(newMessages);
} catch (error) {
res.status(500).json({ msg: error.message });
}
};
CodePudding user response:
Mongoose objects are pretty much immutable, you can't really do that.
The solution is to use .lean()
, which will make Mongoose return simple JSON data, instead of a Mongoose objects array.
Bonus : it's faster.
const message = await messageModel
.find({
conversationId: req.params.messageId,
})
.populate('senderId')
.lean();