Javascript 如何使用node js mongoose在保存后返回json数据

Javascript 如何使用node js mongoose在保存后返回json数据,javascript,json,node.js,mongodb,mongoose,Javascript,Json,Node.js,Mongodb,Mongoose,使用save函数使用post方法插入数据,在相同的方法中,需要获得相同的json数据,即我们插入的带有id的文档 apiRoutes.post('/doctor', function(req, res){ if(!req.body.Name || !req.body.password){ res.json({success: false, msg: 'please pass the username and password'}); }else{

使用save函数使用post方法插入数据,在相同的方法中,需要获得相同的json数据,即我们插入的带有id的文档

apiRoutes.post('/doctor', function(req, res){
      if(!req.body.Name || !req.body.password){
        res.json({success: false, msg: 'please pass the username and password'});
      }else{
        var newUser = new Doctor({
            Name:req.body.Name,
            password : req.body.password,
        });
        newUser.save(function(err){
          if(err){
            res.json({success: false, msg :'username alredy existes'});
          }else{
            res.json({success: true, msg : 'Successfull created user'});
          }
        });
      }
    }); 

在res.json中,您需要返回与documnet的_id相同的文档名和密码

我认为您可以使用
.get()
方法,将
/path/:id
作为第一个参数。大概是这样的:

apiRoutes.get('/doctor/:id', function(req, res){
 // your code goes here
});
因此,从客户端,您可以发送get请求,其中包含以下内容
/doctor/65431
(id)

有关express.get方法的更多信息

请尝试以下方法

apirouts.post('/doctor',函数(req,res){
如果(!req.body.Name | |!req.body.password){
res.json({success:false,msg:'请传递用户名和密码'});
}否则{
var newUser=新医生({
名称:req.body.Name,
密码:req.body.password,
});
newUser.save(函数(err){
如果(错误){
res.send({'success':'false','msg':'username alredy existes'});
}否则{
res.send({'success':'true','msg':'Successfull created user','data':newUser});
}
});
}

}); 根据您的要求,您希望通过POST方法在db中输入名称和密码。然后你就可以做这个了

    apiRoutes.post('/doctor', function (req, res) {
        var newUser = req.Collection;
        var name = req.body.Name;
        var password = req.body.password;
        var record = new newUser({
            name: name,
            password: password,
        });
        if (name && password) {
            record.save(function (err, result) {
                if (err) {
                    res.json({status: 0, message:" username alredy existes"})
                } else {
                    res.json({status: 1, name: name, password: password, message: " Successfull created user"});
                }
            })
        } else {
            res.json({status: 0, msg: "Invalid Fields"});
        }
    });

您也在使用express吗?是的,我在使用express@seI不想在单独的get方法中使用我想在post方法本身中使用response保存后将获取文档id如何在@Shekharyou want mongoid中获取该id此名称和密码存储正确,然后使用id:result.\u id您是否定义了一个集合名称var newUser=req.collection;类似于您的db.js文件是我在dbres.json中定义的({status:1,name:name,password:password,id:result.\u id,message:“Successfull created user”});更换此线路。希望它能正常工作,获取错误dude''res.json({success:true,msg:'Successfull created user':newUser});SyntaxError:意外标记:删除“数据”:新建用户并重试