I can't manage to update the subdocument within the array. I can currently just update the parent-document.
Code where I can update parent-document:
router.put('/:id/:bookid', (req, res) => {
Library.findOne({
_id: req.params.id //parent-id
})
.then(library => {
//Update with new value
library.Name = req.body.newName;
library.save()
.then(library => {
//unrelated code
})
});
});
LibraryScema:
const LibarySchema = new Library({
Name: {
type: String,
required: false
},
books: [BookSchema]
});
bookScema:
const BookSchema = new Schema({
title: {
type: String,
required: false
},
Chapters: [
{
chapterTitle: {
type: String,
required: false
}
}
]
});
I only aim to update the sub-document, not parent- and sub-document at same time.
EDIT:
Earlier attempt:
router.put("/:id/:bookid", (req, res) => {
Library.updateOne(
{ _id: req.params.id, "books._id": req.params.bookid },
{ $set: { "books.$.title": "New value" } }
);
});
The changes don't get saved, no error message.