简体   繁体   中英

How to send response in Node.js

I am developing an app where I am using Node.js and MongoDB in the backend. The scenario is: The user fills all the details and post it to the server. The data is stored in MongoDB database with one ObjectID. Now I want to send that ObjectID as response to the user.

The code is given below:

router.route('/user')

.post(function(req, res) {

        var user = new User(); // create a new instance of the User model
        user.name = req.body.name; // set the user name (comes from the request)

        user.email = req.body.email; // set the user email (comes from the
                                                                        // request)
        user.age = req.body.age; // set the user age(comes
        user.save(function(err) {
                if (err) {
                        res.send(err);
                }

                res.json({
                        message: 'User Created!',

                });
        });

The User Schema is given below:

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

var UserSchema   = new Schema({
        email:                          String,
        name:                           String,
        age:             String,

});

module.exports = mongoose.model('User', UserSchema);

How will I send that ObjectID as response. Please tell me how it can be achieved

Thanks

It seems like you're using an ODM such as Mongoose in addition to MongoDB. You'd have to check that ODM's documentation for what you want to do. But usually, once you have the record whose Id you want, you'd do something like:

user.save(function (err, data) {
  if(err) {
    //handle the error
  } else {
    res.send(200, data._id);
  }
});

Here, we're taking advantage of the fact that every Mongo record's ObjectID is stored as its _id property. If you're only using Mongo and not an ODM, you could also search for the record once it's saved and get the _id property that way.

collection.find(/* search criteria */, function (err, data) {
  //same as before
});

You need a second parameter in callback like this:

user.save(function(err, description){
  var descriptionId = description._id;

  res.send(descriptionId);
});

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