I keep getting an error: TypeError: Cannot read property 'doors' of null. I want to be able to set doors to be nullable, as to be able to avoid this error and simply hit the error response and return 404. However, I am not sure how to do this?
Here is my code:
Data.findOne({
'_id':'6182544c20d538aefe49def0',
'doors.id':doorId
}, {
'doors.$':1
}, function(err, data) {
if (err) {
res.status(404).send('No Matching Door Found')
} else if (data.doors[0].status === 'open') {
res.status(401).send('Door already unlocked')
} else {
res.status(200)
}
})
The error is hit on the third line, where It cannot find a doors object where the ID is equal to doorId.
I have tried setting doors.id to !doors.id, however, this then kept hitting the 404 regardless of what was being entered.
Any help is appreciated, thank you.
Well it seems that your entire query is wrong. I would suggest first to try this query for your needs:
Data.findOne({
'_id':'6182544c20d538aefe49def0',
'doors.id':doorId
}, {
'doors.$':1
}).exec(function(err, data) {
if (err) {
res.status(404).send('No Matching Door Found')
} else if (data.doors[0].status === 'open') {
res.status(401).send('Door already unlocked')
} else {
res.status(200)
}
})
Then I recommend you to read more about MongoDB and Mongoose.