Thomas Simonini Thomas Simonini - 4 months ago 15
Node.js Question

Mongoose schema with object

I try to fill a document in MongoDB with NodeJS, consequently I created a Schema and a post req.

var gameSchema = new Schema({
title: String,
developer: {
name: String,
email: String
},
isBroadcasted: Boolean
});


So I want to populate this schema thanks to a req.

router.post('/android', auth, function(req, res){
// Create a new instance of the Game model
var game = new Game();
game.title = req.body.title;

game.developer.name = req.body.developer.name;
game.developer.email = req.body.developer.email;


enter image description here

But, when I run it there is an error message "TypeError: Cannot read property 'name' of undefined" but I don't understand why because developer.name exists.

Answer

I guess the error is not referring to game.developer.name but to req.body.developer.name.
Try changing your line to

game.developer.name = req.body['developer.name']

as your parameter developer.name is parsed as string, not as nested object.

Comments