1

I'm new to Express/Mongoose and backend development. I am attempting to use a Mongoose subdocument in my Schema and POST data from a form to an MLab database.

I am successfully POSTing to the database when only using the parent Schema, but when I attempt to also POST data from the subdocument I am getting an undefined error. How do I properly POST data from a subdocument?

Here is my Schema:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const bookSchema = new Schema({
  bookTitle: {
    type: String,
    required: true
  },
  author: {
    type: String,
    required: true
  },
  genre: {
    type: String
  }
});

const userSchema = new Schema({
  name: String,
  username: String,
  githubID: String,
  profileUrl: String,
  avatar: String,
  // I've tried this with bookSchema inside array brackets and also 
  //without brackets, neither works
  books: [bookSchema]
});

const User = mongoose.model('user', userSchema);

module.exports = User;

Here is my route where I attempt to POST to the database:

router.post('/', urlencodedParser, (req, res) => {
  console.log(req.body);

  const newUser = new User({
    name: req.body.name,
    username: req.body.username,
    githubID: req.body.githubID,
    profileUrl: req.body.profileUrl,
    avatar: req.body.avatar,
    books: {
      // All of these nested objects in the subdocument are undefined. 
      //How do I properly access the subdocument objects?
      bookTitle: req.body.books.bookTitle,
      author: req.body.books.author,
      genre: req.body.books.genre
    }
  });

  newUser.save()
    .then(data => {
      res.json(data)
    })
    .catch(err => {
      res.send("Error posting to DB")
    });

});
Nick Kinlen
  • 1,356
  • 4
  • 30
  • 58
  • I face the same problem. are you solved this? – Bryan Lumbantobing Jun 23 '20 at 13:35
  • I ended up answering my own question. Look at the next post underneath. I wasn't properly accessing the values using dot notation. `req.body.books.bookTitle` should have been `req.body.bookTitle` for example. Maybe you're facing a similar problem. – Nick Kinlen Jun 23 '20 at 17:45

1 Answers1

2

Figured it out. I wasn't properly accessing the values using dot notation.

books: {
      // All of these nested objects in the subdocument are undefined. 
      //How do I properly access the subdocument objects?
      bookTitle: req.body.books.bookTitle,
      author: req.body.books.author,
      genre: req.body.books.genre
    }

No need to access .books inside of the books object. req.body.books.bookTitle should be req.body.bookTitle and so forth. Leaving this post up in case it helps someone else.

Nick Kinlen
  • 1,356
  • 4
  • 30
  • 58