繁体   English   中英

为什么我的 JavaScript 文件中出现类型错误?

[英]why i am getting type error in my JavaScript file?

为什么我会收到此错误?

我正在从 colt Steele webd bootcamp 学习 Web 开发,但我遇到了这个错误。

$ 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');

据我所知,您缺少分号“;” 在你的括号之后。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM