This is my post model that is stored in mongodb.
const PostSchema = new mongoose.Schema({
text: {
type: String,
required: "Name is required",
},
photo: {
data: Buffer,
contentType: String,
},
likes: [{ type: mongoose.Schema.ObjectId, ref: "User" }],
comments: [
{
text: String,
created: { type: Date, default: Date.now },
postedBy: { type: mongoose.Schema.ObjectId, ref: "User" },
likes: Number,
incomments:[{text:String,postedBy:{ type: mongoose.Schema.ObjectId, ref: "User" }}]
},
],
postedBy: { type: mongoose.Schema.ObjectId, ref: "User" },
I want to insert comments inside comments array i.e insert comments in incomments array inside comments array.
const commentincomment=(req,res)=>{
Post.findOneAndUpdate(
{"_id":req.body.postId,
"comments.text":req.body.comment,
"comments.postedBy":req.body.postedBy
},
{$push:{"comments.$.incomments":{
text:req.body.comtext,
postedBy:req.body.userId
}}}).exec((err, result) => {
if (err) {
return res.status(400).json({
error: err,
});
}
res.json(result);
});
}
I am doing this but the array is not updating. Any suggestions?
You need to typecast variables postId and postedBy containing string value to ObjectId.
Try this:
const mongoose = require('mongoose');
const commentincomment = (req, res) => {
let conditions = {
"_id": mongoose.Types.ObjectId(req.body.postId),
"comments.text": req.body.comment,
"comments.postedBy": mongoose.Types.ObjectId(req.body.postedBy)
};
let postDoc = {
$push: {
"comments.$.incomments": {
text: req.body.comtext,
postedBy: req.body.userId // Also typecast this if required.
}
}
}
let options = {
new: true
};
Post
.findOneAndUpdate(conditions, postDoc, options)
.exec((err, result) => {
if (err) {
return res.status(400).json({
error: err,
});
}
res.json(result);
});
}