javascript - 为什么这个返回的 promise 的值没有更新?
问题描述
我有一个程序,在单击按钮时,应该更新随机获取的 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>
解决方案
好的,感谢 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("/")
});
推荐阅读
- python - 使用输入文件将字符串转换为浮点数
- c++ - 从函数返回向量
- java - 在 W10 环境中使用 JSSC 的 Java 串行应用程序中的 JRE 崩溃
- google-cloud-platform - google_osconfig在谷歌云平台上VM的CPU使用率稳步上升
- javascript - 如何使用 vuetify Grid 获得简单的布局?
- php - 在 Laravel-Vue 项目上运行 npm run watch 时出错
- c++ - 如何调整 FFT 结果中的非指定频率?
- google-chrome - 在 Chrome 开发者工具中,当一个对象带有“constructor”前缀是什么意思?
- ios - MKLocalSearch 如何避免带有“搜索附近”的结果?
- python - 是否有内置方法来检查字符串是否可以转换为浮点数?