所以我正在創建一個投標應用程式,這是投標模型的架構
const bidSchema = new mongoose.Schema({
name: String,
price : Number,
description: String,
location: String,
specilization: String,
image: String,
createdUser: {
type: mongoose.Schema.Types.ObjectId,
ref: User
},
highestBidder: {
highBidderName: {
type: mongoose.Schema.Types.ObjectId,
ref: User
},
highPrice: Number,
},
previousBidders: [{previousName: {
type: mongoose.Schema.Types.ObjectId,
ref: User
} , previousPrice: Number}],
isClosed: {
type: Boolean,
enum:[true]
}
})
這是我的出價路線,將在其中添加出價
route.post('/:id/submitbid',isloggedin, async (req,res) => {
const {id} = req.params
const bids = await Bid.findById(id)
if(! bids.highestBidder){
bids.highestBidder.highBidderName = req.user._id
bids.highestBidder.highPrice = req.body.highPrice
await bids.save()
console.log('if worked')
res.redirect(`bids/${bids._id}`)
} else {
const previousName = bids.highestBidder.highBidderName
const previousPrice = bids.highestBidder.highPrice
bids.highestBidder.highBidderName = req.user._id
bids.highestBidder.highPrice = req.body.highPrice
bids.previousBidders.push({previousName,previousPrice})
console.log('else worked')
await bids.save()
res.redirect(`/bids/${bids._id}`)
}
})
最初,bids.highestBidder 部分不包含任何內容,所以當我在執行 /:id/submit 路由之前控制臺記錄出價物件時,這就是我在控制臺中得到的。
{
_id: new ObjectId("616944da40c3b2ac3779f93b"),
name: 'gratus',
price: 10,
description: ';fdja;dfja;ldf;a',
location: 'india',
image: 'https://source.unsplash.com/random/200x200?sig=1',
previousBidders: [],
createdUser: {
_id: new ObjectId("61687ab4a79b1fa356b9fca5"),
email: '[email protected]',
username: 'gratus',
__v: 0
},
__v: 0
可以看到沒有bids.highestBidder存在,所以當我執行/:id/submitbid post路由時,if陳述句應該執行,但這是我在執行該路由后在控制臺中得到的
else worked
我不知道為什么其他作業,問題是如果我現在控制臺記錄我的出價物件,這就是我得到的
else worked
{
highestBidder: {
highBidderName: {
_id: new ObjectId("61687ab4a79b1fa356b9fca5"),
email: '[email protected]',
username: 'gratus',
__v: 0
},
highPrice: 5
},
_id: new ObjectId("616944da40c3b2ac3779f93b"),
name: 'gratus',
price: 10,
description: ';fdja;dfja;ldf;a',
location: 'india',
image: 'https://source.unsplash.com/random/200x200?sig=1',
previousBidders: [ { _id: new ObjectId("616944e740c3b2ac3779f943") } ],
createdUser: {
_id: new ObjectId("61687ab4a79b1fa356b9fca5"),
email: '[email protected]',
username: 'gratus',
__v: 0
},
__v: 1
}
它正在創建一個空的 previousBidders 陣列,這破壞了我的整個應用程式。我真的很感激任何解決方案。
uj5u.com熱心網友回復:
Mongoose 模型實體不是普通物件。他們通常有特殊的方法來生成您在執行 console.log 時看到的 json 輸出。這意味著該欄位可能很好地存在,但由于未設定其子屬性,因此不會在控制臺輸出中呈現。
由于highestBidder 具有子屬性,因此由于這些屬性,您正在執行的默認布林值if-check 可能回傳true。您可以通過以下方式避免這種情況:
if ( !bids.highestBidder || !bids.highestBidder.highBidderName ) {
...
}
這實作的是,如果highestBidder 沒有被宣告,它會立即跳轉執行if 中的代碼。否則,它還會檢查highestBidderName 屬性是否有值,如果沒有找到則執行if 代碼塊。這樣您就可以避免貓鼬添加的幽靈子屬性影響您的條件結果。
可能有比這更優雅的解決方案,但這是一種快速簡便的方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/321271.html
標籤:javascript 节点.js MongoDB 表达 猫鼬
