简体   繁体   中英

.then is undefined when I try to save in MongoDB

I'm new to node.js. I got this message:

TypeError: Cannot read property 'then' of undefined

Here is the code:

router.post("/signup", (req, res) => {
  const userRegister = new UserRegister({
    _id: new mongoose.Types.ObjectId(),
    nickname: req.body.nickname,
    email: req.body.password,
    password: req.body.password,
    level: 0
  });
  console.log(req.body.nickname + " " + req.body.email + " " + req.body.password);
  userRegister
    .save()
    .then(doc => {
      console.log(doc);
      res.status(200).json({
        message: "User created"
      });
    })
    .catch(err => {
      if (err)
        console.log("error => " + err)
      res.status(409).json({
        message: "ERROR"
      })
    });
});

and the Schema:

const mongoose = require("mongoose");

const userRegister = mongoose.Schema({
  _id : mongoose.Schema.Types.ObjectId,
  nickname: String,
  email: String,
  password: String,
  level: Number
});

module.exports = mongoose.model("UserRegister", userRegister); 

I don't really understand why it says ".then undefined". (the body is good)

check if the model is the promising type or not if this is not the promising then use callback

mongoose promises

assert.ok(user instanceof Promise); // this return ture or false

router.post("/signup", (req, res) => {
      const userRegister = new UserRegister({
        _id: new mongoose.Types.ObjectId(),
        nickname: req.body.nickname,
        email: req.body.password,
        password: req.body.password,
        level: 0
      });

      console.log(req.body.nickname + " " + req.body.email + " " + req.body.password);


      var user = userRegister.save()

     assert.ok(user instanceof Promise); 

     // if assert.ok return true then use user.then 
    // else use callback  userRegister.save( function(doc){ })    

      user.then(doc => {
        console.log(doc);
        res.status(200).json({
          message: "User created"
        });
      })
      .catch(err => {
        if (err)
          console.log("error => " + err)
        res.status(409).json({
          message: "ERROR"
        })
      });
    });

It seems like function "save" does not return Promise. But in source code it does... https://github.com/Automattic/mongoose/blob/master/lib/model.js#L385

Also you can try "create" method.
https://github.com/Automattic/mongoose/blob/master/lib/model.js#L2646

Maybe it will be hellpfull:

   const result = new SomeModel({...});

   new Promise((resolve, reject) => {
      // Save model
      result.save(err => {
        if (err) {
          return reject(new Error(`Error with exam ersult save... ${err}`));
        }
        // Return saved model
        return resolve(result);
      })
      .then(res => {
        return res;
      })
      .catch(err => {
        throw new Error(err);
      });
router.post("/signup", async (req, res) => {
    try{
        const userRegister = await UserRegister.create({
            _id: new mongoose.Types.ObjectId(),
            nickname: req.body.nickname,
            email: req.body.password,
            password: req.body.password,
            level: 0
        });
    }
    catch(err){
        console.log("error => " + err)
        res.status(409).json({
        message: "ERROR"
        })
    }

    console.log(userRegister);
    res.status(200).json({
        message: "User created"
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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