我正在為教育目的制作一個簡單的待辦事項串列應用程式,并且我正在使用自定義路由功能,所以如果用戶鍵入自定義路由,我正在檢查資料庫中是否存在具有該名稱的集合,如果它不存在創建它,但貓鼬多次創建同一個集合而不是一個。
我對此感到震驚,您是否在我的代碼中看到了可能觸發此類問題的內容?
const express = require("express")
const mongoose = require("mongoose");
const app = express()
const _ = require("lodash")
app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: true}))
app.use(express.static('static'));
app.use('/dep/css', express.static(`${__dirname}/node_modules/bootstrap/dist/css`))
app.use('/dep/js', express.static(`${__dirname}/node_modules/bootstrap/dist/js`))
app.use('/dep/js', express.static(`${__dirname}/node_modules/particlesjs/dist`))
app.use('/dep/js', express.static(`${__dirname}/node_modules/@fortawesome/fontawesome-free/js`))
// --------------------- CONNECTION -----------------------------
mongoose.connect('mongodb://localhost:27017/todoDB');
mongoose.connection.on('connected', function () {
console.log('Mongoose default connection open to 27017');
});
// -------------------------- MODELS AND SCHEMAS -------------------
const itemsSchema = new mongoose.Schema({
task: {
type: String,
required: [true, "Task cannot be empty !"]
}
})
const Item = mongoose.model("Item", itemsSchema);
const listSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "List name cannot be empty !"]
},
items : [itemsSchema]
})
const List = mongoose.model("List", listSchema);
const dateOptions = {
day:"numeric",
weekday:"long",
month : "long",
year : "numeric"
}
const currentDay = new Date().toLocaleDateString("en-US",dateOptions)
// --------------------- GETS ------------------------------------
app.get("/", (req, res) => {
Item.find((err, items) => {
if (err) {
console.log(err);
} else {
res.render('list', {
listName: currentDay,
newItems:items
});
}
})
})
app.get("/:customList", (req, res) => { //GET A REQUEST TO A CUSTOM ROUTE
const customList = _.capitalize(req.params.customList) //GRAB THE CUSTOM ROUTE STRING
List.findOne( {name:customList},(err,listFound) =>{ //SEARCH IF THE COLLECTION EXISTS
if (err){ console.log(err) }else{
if(listFound){ //IF IT EXISTS RENDER THE VIEW WITH THE COLLECTION DATA
res.render('list', {
listName: listFound.name,
newItems:listFound.items
});
}else{ //IF ITS NOT THEN CREATE IT WITH THE GIVEN NAME
const list = new List({
name:customList
})
list.save()
res.redirect(`/${customList}`)
console.log("list created !")
}
}
} )
})
// ------------------- POSTS ------------------------------
app.post("/", (req,res) =>{
let item = new Item({
task: req.body.newItem
})
if ( req.body.list === currentDay ){
item.save((err)=>{ err?console.log(err):console.log("saved") })
res.redirect("/")
}else{
List.findOne( {name:req.body.list},(err,listFound) =>{
if (err){ console.log(err) }else{
listFound.items.push(item)
listFound.save()
res.redirect(`/${req.body.list}`)
}
} )
}
} )
app.post("/delete", (req,res) =>{
if ( req.body.list === currentDay ){
Item.findByIdAndRemove({ _id: req.body.checkbox },(err)=>err?console.log(err):console.log("deleted"))
res.redirect("/")
}else{
List.findOneAndUpdate( {name:req.body.list},{ $pull: { items: {_id : req.body.checkbox} } },(err,listFound) =>{
err ? console.log(err) : res.redirect(`/${req.body.list}`)
})
}
})
// -------------------- SERVER --------------------------
const server = app.listen(3000, () => {
console.log(`Todolist app server is running on port ${server.address().port}`);
})
這就是我在創建集合后從我的資料庫服務器得到的,例如在這里我創建了一個名為“yolo”的集合,當我顯示我的集合時......:
> db.lists.find()
{ "_id" : ObjectId("61d9d2c74eff3d67c18430f1"), "name" : "Yolo", "items" : [ ], "__v" : 0 }
{ "_id" : ObjectId("61d9d2c74eff3d67c1843100"), "name" : "Yolo", "items" : [ ], "__v" : 0 }
{ "_id" : ObjectId("61d9d2c74eff3d67c18430f4"), "name" : "Yolo", "items" : [ ], "__v" : 0 }
{ "_id" : ObjectId("61d9d2c74eff3d67c18430f7"), "name" : "Yolo", "items" : [ ], "__v" : 0 }
{ "_id" : ObjectId("61d9d2c74eff3d67c18430fa"), "name" : "Yolo", "items" : [ ], "__v" : 0 }
{ "_id" : ObjectId("61d9d2c74eff3d67c18430fd"), "name" : "Yolo", "items" : [ ], "__v" : 0 }
uj5u.com熱心網友回復:
我認為您對帶有檔案的術語集合感到困惑,在查詢后發現您得到的是串列集合中存在的檔案。您可以執行以下操作以使串列中的名稱唯一,但這不是標準解決方案,對于唯一的屬性,您可能需要在此處查看檔案
const listSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "List name cannot be empty !"],
unique: true
},
items : [itemsSchema]
})
const List = mongoose.model("List", listSchema);
uj5u.com熱心網友回復:
的保存()函式是異步的。當您redirect在呼叫后立即呼叫時save,您會遇到競爭條件,它將繼續回圈并呼叫 save 然后重定向,直到其中一個 save 呼叫實際完成。
要解決此問題,請將redirect呼叫移至傳遞給的回呼函式save
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/406423.html
標籤:
