mongoose do not return saved document in callback

徘徊边缘 提交于 2021-02-08 09:52:56

问题


I am trying to save a new record using mongoose. I am not getting the saved document in the callback.

 app.post("/register",(req,res) => {
    let userData = req.body;
    let user = new User(userData)
    user.save().then((err,doc) => {
        res.json({"success":true,"data":doc});
        console.log(doc);
    })    
});

I am getting doc:1. While I should get the whole document. Please help me.

  "dependencies": {
    "body-parser": "^1.18.2",
    "crypto-js": "^3.1.9-1",
    "express": "^4.15.5",
    "mongoose": "^4.11.13"
  }

回答1:


You're using promises, then callback provides only one parameter - result of asynchronous call. To catch error, catch callback should be used:

app.post("/register", (req, res) => {
    let userData = req.body;
    let user = new User(userData);
    user
      .save()
      .then(doc => {
        console.log(doc);
        res.json({ success: true, data: doc });
      })
      .catch(err => {
        console.log(err);
        res.status(500).send({ error: err });
      });
});


来源:https://stackoverflow.com/questions/46569248/mongoose-do-not-return-saved-document-in-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!