简体   繁体   English

如何在Node.js中发送响应

[英]How to send response in Node.js

I am developing an app where I am using Node.js and MongoDB in the backend. 我正在开发一个在后端使用Node.js和MongoDB的应用程序。 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. 数据使用一个ObjectID存储在MongoDB数据库中。 Now I want to send that ObjectID as response to the user. 现在,我想发送该ObjectID作为对用户的响应。

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. 我将如何发送该ObjectID作为响应。 Please tell me how it can be achieved 请告诉我如何实现

Thanks 谢谢

It seems like you're using an ODM such as Mongoose in addition to MongoDB. 似乎除了MongoDB外,您还使用了Mongoose这样的ODM。 You'd have to check that ODM's documentation for what you want to do. 您必须检查ODM的文档以了解您想做什么。 But usually, once you have the record whose Id you want, you'd do something like: 但是通常,一旦有了所需记录的ID,就可以执行以下操作:

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. 在这里,我们利用了每个Mongo记录的ObjectID作为其_id属性存储的事实。 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. 如果您仅使用Mongo而不是ODM,则还可以在保存后搜索记录,并以这种方式获取_id属性。

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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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