Why is this error occurring?
I am currently studying web development through Colt Steele's web bootcamp and encountered this issue.
$ node user.js
mongo connection is open
D:\web development practice\mongoose_relationship\Models\user.js:44
u.addresses.push({
^
TypeError: Cannot read properties of null (reading 'addresses')
at addAddress (D:\web development practice\mongoose_relationship\Models\user
.js:44:7)
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/relationshipDemo', { useNewUrlParser: true })
.then(() => {
console.log("mongo connection is open")
})
.catch(e => {
console.log("oh no mongoose connection error");
console.log(e);
})
const userSchema = new mongoose.Schema({
first: String,
last: String,
addresses: [{
_id: { id: false },
street: String,
city: String,
state: String,
country: String
}]
})
const User = mongoose.model('User', userSchema);
const makeUser = async () => {
const u = new User({
first: 'Harry',
last: 'Potter'
})
u.addresses.push({
street: 'baker street',
city: 'london',
state: 'london',
country: 'uk'
})
await User.deleteMany();
const res = await u.save();
console.log(res);
}
const addAddress = async (id) => {
const u = await User.findById(id);
u.addresses.push({
street: 'florida street',
city: 'new york',
state: 'new york',
country: 'usa',
})
const res = await u.save();
console.log(res);
}
addAddress('62ceae58cbb52805b8150ce9');