so I am creating an bidding app, this is the schema for the bidding model
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]
}
})
this is my bid route in which a bid will get added
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}`)
}
})
initially , the bids.highestBidder part don't contain anything, so when I console logged the bid object before the execution of the /:id/submit route and this is what I got in the console.
{
_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: 'gratus@gratus.com',
username: 'gratus',
__v: 0
},
__v: 0
as one can see that there is no bids.highestBidder exist, so when I execute the /:id/submitbid post route, the if statement should execute, but this is what I am getting in the console after executing that route
else worked
I have no idea why else is working , and the problem with is that if I now console logged my bid object, this is what I am getting
else worked
{
highestBidder: {
highBidderName: {
_id: new ObjectId("61687ab4a79b1fa356b9fca5"),
email: 'gratus@gratus.com',
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: 'gratus@gratus.com',
username: 'gratus',
__v: 0
},
__v: 1
}
it is creating an empty previousBidders array, which breaks my whole application. I would really appreciate any solution.