Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

updateOne $set function won't work in Mongoose

I'm trying to update the subdocument books within the array without success. The new data won't get saved.

Express:

router.put("/:id/:bookid", (req, res) => {
  Library.updateOne(
    { _id: req.params.id, "books._id": req.params.bookid },
    { $set: { "books.$.title": "New value" } }
  );
});

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
      }
    }
  ]
});

What am I doing wrong?

EDIT:

Libary Table:

{
    "_id": {
        "$oid": "12345"
    },
    "Name": "A random libary",
    "Books": [{
        "_id": {
            "$oid": "1"
        }
        "title": "TitleExample",
        "Chapters": [{
            chapterTitle: "first chapter etc"
        }]             
    },
    {
        "_id": {
            "$oid": "2"
        }
        "title": "Another book"  ,
        "Chapters": [{
            chapterTitle: "first chapter etc"
        }]  
    }]
}
like image 767
skylake Avatar asked Feb 06 '26 12:02

skylake


1 Answers

You can try this:

router.put("/:id/:bookid", (req, res) => {
    Library.findOne({ _id: req.params.id, "books._id": req.params.bookid }).exec(function(err,result) {
        if (err) throw err;
        if (result) {
            result.books.title = "new value";
            result.save()
            console.log("new value")
        } else {
            console.log("not found")
        }
    });
});
like image 130
ŞükSefHam Avatar answered Feb 09 '26 10:02

ŞükSefHam