我有一个程序,在点击按钮时,"喜欢"随机获取的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>
通过console logging (result)检查promise的状态。如果它返回一个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("/")
});
我想这应该行得通。
好吧,感谢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("/")
});