简体   繁体   中英

Save POST data To MongoDB: Node.js

I'am new with node.js.I Need to save data from HTML page use - form (user name, password, email etc)in Mongodb. I have this code:

var Schema = new mongoose.Schema({
      _id    : String,
      name: String,
      age   : Number
});

var user = mongoose.model('emp', Schema);

    app.post('/new', function(req, res){
      new user({
        _id    : req.body.email,
        name: req.body.name,
        age   : req.body.age        
      }).save(function(err, doc){
        if(err) res.json(err);
        else    res.send('Successfully inserted!');
      });
    });

<form action="/new" method="POST">
<label for="email">Email: </label>
<input type="email" name="email" /><br />
<label for="name">Name: </label>
<input type="text" name="name" /><br />
<label for="age">Age: </label>
<input type="number" name="age" /><br />
<input type="submit"/>

When I run server. Trying to save some data. I see message "Cannot read property 'email' of undefined" "TypeError: Cannot read property 'email' of undefined" Somebody help me please with this misunderstood. Thans a lot!

Also you don't need to define _id in your schema, it gets automatically created. Maybe you meant to define email : String so it matches your req.body.email

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM