gpt4 book ai didi

javascript - 如何在 Node.js 中发送响应

转载 作者:行者123 更新时间:2023-12-02 16:45:32 24 4
gpt4 key购买 nike

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

最佳答案

除了 MongoDB 之外,您似乎还在使用 ODM,例如 Mongoose。您必须检查 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
});

关于javascript - 如何在 Node.js 中发送响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27151993/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com