0

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.

ipid
  • 253
  • 1
  • 4
  • 16
  • What code have you tried using? – samanime Apr 03 '18 at 17:26
  • I tried to update with `$set`, but was unsuccessful (must have done something wrong, as this is new to me). And `"$elemMatch"` (worked to `get` that specific sub-document, but couldn't update with that solution, again, could've done something wrong). – ipid Apr 03 '18 at 17:31
  • Can you show examples of the code you tried so we can go from there? Updating a `Book` directly even if you got the reference from `Library` shouldn't really be any different, so seeing your exact code may point to the issue. – samanime Apr 03 '18 at 17:33
  • @samanime Updated the answer. – ipid Apr 03 '18 at 20:59

0 Answers0