I have the following schema in MongooseJS:
const ParentChildCommentSchema = new mongoose.Schema({
date: Date,
from: { type:mongoose.Schema.Types.ObjectId, ref:'Parent' },
message: String,
});
const ParentChildSchema = new mongoose.Schema({
child: { type:mongoose.Schema.Types.ObjectId, ref:'Child' },
comments: [ ParentChildCommentSchema ],
});
const ParentSchema = new mongoose.Schema({
name: String,
description: String,
children: [ ParentChildSchema ],
});
Where Parents have Children, and each Parent/Child relationship can have an array of comments.
I'm trying to push a comment with
const query = {
"_id": parentId,
"children._id": parentChildId,
};
const update = {
"$push": {
"children.$.comments": {
"date": Date.now(),
"from": parentId,
"message": message,
}
}
};
Pack.findOneAndUpdate(query, update, err => ...)
The query isn't throwing any errors. But no comment is being added. What am I doing wrong?
"$push"to$push$in this:children.$.comments?childrenis itself an array. Usingchildren.$.commentswill target the item inchildrenspecified in the query.