I am having issues trying to get the ‘runValidators’ option to work. My post schema has an comments.replies.creator field that has required set to true but each time a new reply gets added to the database and the creator field is empty it does not complain, like not at all :
module.exports.createReply = async (req, res) => {
const user_ID = req.body.creatorId;
const post_ID = req.params.id;
const comment_ID = req.body.commentId;
const reply = {
creatorId: user_ID,
creator: req.body.creator ? req.body.creator : null,
body: req.body.body,
timestamp: new Date().getTime(),
};
const query = { _id: post_ID };
const update = { $push: { "comments.$[elem].replies": reply } };
const options = {
projection: { _id: comment_ID, comments: 1 },
upsert: true,
new: true,
runValidators: true,
arrayFilters: [{ "elem._id": comment_ID }],
};
try {
return await PostModel.findByIdAndUpdate(
query,
update,
options,
(err, doc) => {
console.log(err);
console.log(doc);
}
);
} catch (err) {
console.log(err);
}
};
my model
const PostSchema = nongoose.Schema({
.....
comments: {
required: true,
type: [
{
.....
body: {
type: String,
required: true,
trim: true,
},
......
replies: {
require: true,
type: [
{
isReady: {
type: Boolean,
default: true,
},
creatorId: {
type: String,
required: true,
trim: true,
},
creator: {
type: String,
required: true,
trim: true,
},
body: {
type: String,
required: true,
trim: true,
min: [3, "Must be at least 6, got {VALUE}"],
},
timestamp: Number,
},
],
},
},
],
},
}
)