繁体   English   中英

如何在Node.js中发送响应

[英]How to send response in Node.js

我正在开发一个在后端使用Node.js和MongoDB的应用程序。 场景是:用户填写所有详细信息并将其发布到服务器。 数据使用一个ObjectID存储在MongoDB数据库中。 现在,我想发送该ObjectID作为对用户的响应。

代码如下:

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!',

                });
        });

用户架构如下:

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

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

});

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

我将如何发送该ObjectID作为响应。 请告诉我如何实现

谢谢

似乎除了MongoDB外,您还使用了Mongoose这样的ODM。 您必须检查ODM的文档以了解您想做什么。 但是通常,一旦有了所需记录的ID,就可以执行以下操作:

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

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

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

您需要在回调中添加第二个参数,如下所示:

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