Saturday, 6 May 2017

Updating to a Mongo subdocument in node route

I have a simple schema, representing an Author, which holds a sub-document of books they've authored.

var bookSchema = new Schema ({
      title: {type: String},
      comments: [{type: String}]
});

var schema = new Schema ({
     fullName: {type: String, required: true, unique: true}, 
     bookList: [{bookSchema}]
});

When I attempt to add a new book (see below) to my author, the correct author is updated, with a new instance of a book. However, none of the values are added to the sub-document.

const length = req.body.bookList.length - 1;
const bookTitle = req.body.bookList[length];
console.log(bookTitle);
author.bookList.push({ title: bookTitle });

I believe the issue is related to the schema of my bookList not being visible, as it seems to always only add a new instance of the object, _id

  {
    "_id" : ObjectId("590e52dfe804ef4e74094faa"),
    "fullName" : "George Orwell",
    "bookList" : [
        {
            "_id" : ObjectId("590e52e9e804ef4e74094fab")
        },
        {
            "_id" : ObjectId("590e5475e804ef4e74094fac")
        }
    ],
    "__v" : 1
  }

Any advice/tips will be greatly appreciated, also please let me know if anything is unclear, still very new to this topic.

Thanks!



via Joshy Boy

No comments:

Post a Comment