简体   繁体   English

.then在我尝试保存在MongoDB中时未定义

[英].then is undefined when I try to save in MongoDB

I'm new to node.js. 我是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". 我不太明白为什么它说“ .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); assert.ok(Promise的用户实例); // this return ture or false //此返回值或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. 似乎函数“保存”不会返回Promise。 But in source code it does... https://github.com/Automattic/mongoose/blob/master/lib/model.js#L385 但是在源代码中确实如此... 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 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"
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我尝试将 Object 从 api 添加到我的 mongodb atlas db NODE.JS 时,我变得不确定 - I get undefined when i try to add an Object from an api to my mongodb atlas db NODE JS 当我尝试从提交的表单中保存值时,本地存储给出未定义的结果 - Localstorage giving Undefined result when I try to save values from a submitted form 值错误:未定义,当我尝试使用节点/快速服务器将一些信息保存到 mongo db 集合时 - Error of value: undefined,when i try to save some information to a mongo db collection using a node/express server 当我尝试查找和修改mongodb错误 - mongodb wrong when i try to findandmodify 当我尝试显示数组中的 Object 时未定义 - Object in array is undefined when I try to display it 当我尝试访问参数时变得不确定 - Getting undefined when i try to access parameter 当我保存方法的返回时,它保存未定义 - When I save the return of the method it saves undefined 为什么在尝试获取此骨干模型的属性时未定义? - Why is this Backbone model's attribute undefined when I try to get it? 当我尝试从Ajax进行POST时PHP未定义的索引数据 - PHP Undefined index data when I try to POST from Ajax 当我尝试 select 它的属性时,documentCreatElement(div) 返回 undefined - documentCreatElement(div) returns undefined when I try to select it's attribute
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM