我有一個程式,單擊按鈕后,隨機獲取的 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>
uj5u.com熱心網友回復:
通過控制臺日志記錄(結果)檢查承諾的狀態。如果它回傳一個pendingpromise,try async-awaitwhich 將決議promise,然后執行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("/")
});
我認為它應該作業。
uj5u.com熱心網友回復:
好的,感謝 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("/")
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/335608.html
標籤:javascript 节点.js MongoDB 表达 承诺
