【问题标题】:Issue with update in MongooseMongoose 中的更新问题
【发布时间】:2019-12-03 07:49:27
【问题描述】:

我写了一个简单的更新函数。它可以正常工作几分钟,然后又不能正常工作。我哪里错了?请帮我。我使用 PUT 作为我的方法。

代码

accept = (req, res) => {
    this._model.update({
        user: new mongoose.Types.ObjectId(req.params.uid)
    }, {
        $set: {
            status: 'active'
        }
    }, (err, obj) => {
        if (err || !obj) {
            res.send(err);
        } else {
            res.send(obj);
        }
    });
}

型号

  {
   "_id":"5d3189a00789e24a23438a0d",
   "status":"pending",
    "user":ObjectId("5d3189a00789e24a23438a0d"),
   "code":"CT-123-345-234-233-423344",
   "created_Date":"2019-07-19T09:13:04.297Z",
   "updated_Date":"2019-07-19T09:13:04.297Z",
   "__v":0
  }

请求

api.abc.com/api/accept/5d3189a00789e24a23438a0d

有时它正在返回值,有时是 null。

【问题讨论】:

  • 你得到的null是“err”变量,它返回它,因为它与!obj匹配。你确定你发送正确的uid,控制台记录吗?提示:您不要在 mongoose.Types.ObjectId 上新建“新”
  • 它将转到else 部分@noitse
  • 按照所有的编码逻辑,这是没有意义的,如果你检查你的 if 语句,它会说是否有错误,或者没有 obj(!将考虑 null,未定义为 true)它将进入第一个块。没有逻辑它去 else 并将 obj 作为 null 发送。
  • 我的问题是它总是会在某个时候阻塞它的返回值,而在其他时候阻塞为null
  • 看起来您的用户对象 id 以字符串形式存储在集合 "user":"ObjectId(5d3189a00789e24a23438a0d)" 中,它应该是 objectId 类型。

标签: node.js mongodb api mongoose crud


【解决方案1】:

您可以使用以下代码来确保模型与连接相关联。这可能是与数据库的连接问题。

const config = require('./config');
console.log('config.database.url', config.database.url);

return mongoose.createConnection(config.database.url, {
    useMongoClient: true
})
.then((connection) => {
    // associate model with connection
    User = connection.model('User', UserSchema);

    const user = new User({
        email: 'someuser@somedomain.com',
        password: 'xxxxx'
    });

    const prom = user.update();

    // Displays: 'promise: Promise { <pending> }'
    console.log('promise:', prom);

    return prom
    .then((result) => {
        // Don't see this output
        console.log('result:', result);
    })
    .catch((error) => {
        // Don't see this output either
        console.log('error:', error);
    });
})
.catch((error) => {
    console.log(error);
});  

【讨论】:

    【解决方案2】:

    我觉得你需要使用promise或者async/await,试试这个

    accept = async (req, res) => {
      try {
        const result = await this._model.update({
          user: new mongoose.Types.ObjectId(req.params.uid)
        }, {
            $set: {
              status: 'active'
            }
          });
        return res.send(result);
      } catch (e) {
        return res.send(e);
      }
    };
    
    

    【讨论】:

    • 面临同样的问题。我第一次得到成功代码的响应,下一次我得到成功代码的空值。我没去catch
    • 您是否在下次通话中更新相同的状态? @克里斯
    猜你喜欢
    • 1970-01-01
    • 2017-05-29
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多