我不明白特定的異步 javascript 代碼:我有幾行由 node.js 運行的非常簡單的 javascript,我在其中查詢本地 mongoDB,主要是這樣做的:需要貓鼬承諾連接到數(shù)據(jù)庫mongoose.connect("...url to my local mongoDB...")
.then(console.log("Connected to DB..."))創(chuàng)建模式從模式創(chuàng)建模型定義一個異步函數(shù)來創(chuàng)建一個新對象,將其保存為 mongoDB 中的文檔,并控制臺記錄嘗試保存文檔后返回的結(jié)果。我不明白的是 console.log("Connect to DB") 和 console.log(document.save() 的結(jié)果) 的順序:確實,當保存沒有錯誤時,順序似乎沒問題:我首先有“連接到數(shù)據(jù)庫...”,然后是返回的保存文檔:但是當由于不遵守某些要求而出現(xiàn)數(shù)據(jù)驗證錯誤時,則在“連接到數(shù)據(jù)庫”之后打印“連接到數(shù)據(jù)庫”:關(guān)于代碼的結(jié)構(gòu),我不明白為什么在打印錯誤后打印“已連接到數(shù)據(jù)庫...”。我懷疑異步代碼是原因,但我不明白為什么。這幾行非常簡單的代碼來自“使用 Mosh 編程”課程,我們可以在他的控制臺上看到完全相同的行為。更多代碼細節(jié): const mongoose = require("mongoose") mongoose .connect(my_mongo_db_url) .then(() => console.log("Connected to DB")) .catch(err => console.log("Could not connect to DB")) const courseSchema = new mongoose.Schema({ ...course schema... }) const Course= mongoose.model("Course", courseSchema ) async function createCourse(){ const course = new Course({ ...new course values... }) try { const result = await course.save()} catch (err) { console.log(err.message)} } createCourse()
在 node.js 和 mongoose 建立 mongodb 連接之前,如何拒絕數(shù)據(jù)模式?
喵喔喔
2023-05-19 14:46:35