【问题标题】:Why is the value of this returned promise not updating?为什么这个返回的 promise 的值没有更新?
【发布时间】:2021-12-09 08:35:41
【问题描述】:

我有一个程序,单击按钮后,随机获取的 MongoDB 文档的“喜欢”属性应该会更新。但是,事实并非如此。我可以通过按钮调用获取的文档,而不是实际更新它:

MongoClient.connect(DBconnection, { useUnifiedTopology: true })
  .then(client => {
    const db = client.db(database);
    const collection = db.collection(table);

    //R has been previously defined as a random number
    let doc = function(data) {
      return db.collection(table).find().limit(-1).skip(R - 1).next()
        .then(results => { return results })
    }
    
    //This is supposed to update the value of the randomly fetched document
    app.post("/", (req, res) => {
      let w = doc()
      w.then(function(results) {
        console.log(results) //This correctly returns the random document
      })
      //This line is meant to update document "w", but it does not.
      db.collection(table).updateOne({ w }, { $set: { likes: "clicked" + R } })
        .then(result => {
          res.redirect("/")
        })
        .catch(error => console.error(error))
    });
  });

ejs文件中的按钮就这么简单:

<form action="/" method="POST">
    <button id="updoot" type="submit">upvote</button>
</form>

【问题讨论】:

  • updateOne 函数是否将 promise 作为过滤参数?那是有线的!
  • 您可能想根据w 字段进行更新?然后使 post "/" 处理程序异步,还在 doc() 之前添加 await 关键字,提示:_ 并且您不需要从 updateOne 捕获错误,express.js 会为您完成,只需返回承诺对象。

标签: javascript node.js mongodb express promise


【解决方案1】:

通过控制台记录(结果)检查承诺的状态。如果它返回一个pending 承诺,请尝试async-await 这将解决承诺,然后执行res.redirect。

app.post("/", async (req, res) => {
      let w = await doc()
      const updatedData = await db.collection(table).updateOne({ w }, { $set: { likes: "clicked" + R } })
      res.redirect("/")
  });

我认为应该可以。

【讨论】:

  • 这似乎不适合我。控制台返回:{ acknowledged: true, modifiedCount: 0, upsertedId: null, upsertedCount: 0, matchedCount: 0 } 为 updatedData 的值。
【解决方案2】:

好的,感谢 jkalandarov 的贡献,我可以通过添加一个额外的步骤来解决它:请求 w 的 ObjectId 并将其用作过滤器,而不是 w 的返回承诺:

app.post("/", async (req, res) => {
      let w = await doc()
      var oid = w._id
      let updatedData = await db.collection(table).updateOne({"_id":ObjectId(oid)}, { $set: { likes: "clicked" + R } })

      res.redirect("/")
  });

【讨论】:

  • 干得好!我应该考虑通过选择 id 来更新。
猜你喜欢
  • 2021-01-11
  • 1970-01-01
  • 2016-02-24
  • 2020-03-13
  • 1970-01-01
  • 2019-03-15
  • 2013-03-25
  • 2015-10-24
  • 1970-01-01
相关资源
最近更新 更多