简体   繁体   English

为什么我不断收到TypeError:用户不是构造函数?

[英]Why do I keep getting TypeError: User is not a constructor?

I'm practicing creating models and routes and am using postman to send a POST request to test it out. 我正在练习创建模型和路线,并正在使用邮递员发送POST请求以对其进行测试。 However, I keep getting the user is not a constructor error. 但是,我不断得到的用户不是构造函数错误。

index.js (route) index.js(路由)

const express = require('express')
require('./db/mongoose')
const User = ('./models/user')

const app = express()
const port = process.env.PORT || 3000

app.use(express.json())

app.post('/users', (req, res) => {
    const user = new User(req.body)

    user.save().then(() => {
        res.send(user)
    }).catch(() => {

    })
})

app.listen(port, () => {
    console.log(port + ' is aliiiiiiiive!')
})

User (schema) 用户(模式)

const mongoose = require('mongoose')
const validator = require('validator')

const User = mongoose.model('User', { 
    name: {
        type: String,
        required: true, 
        trim: true
    }, 
    email: {
        type: String,
        require: true,
        trim: true, 
        lowercase: true,
        validate(value) {
            if(!validator.isEmail(value)) {
                throw new Error('Email is invalid')
            }
        }
    },
    age: {
        type: Number,
        default: 0,
        validate(value) {
            if(value < 0) {
                throw new Error('Age must be a positive number.')
            }
        }
    },
    password: {
        type: String,
        trim: true,
        lowercase: true,
        required: true,
        minlength: 7,
        validate(value) {
            if( value.toLowerCase().includes("password")) {
                throw new Error("Password can't be 'password'.")
            }
        }
    }
})

module.exports = User

mongoose.js mongoose.js

const mongoose = require('mongoose')

mongoose.connect('mongodb://127.0.0.1:27017/task-manager-api', {
    useNewUrlParser: true,
    useCreateIndex: true
})

I expect it to send back an object with the following information I'm sending on Postman: 我希望它能将我在Postman上发送的以下信息发送回一个对象:

{
    "name": "Michael",
    "email": "email@eail.com",
    "password": "ThisIsAPassword"
}

You have to define a userSchema before compiling the model, like this: 您必须在编译模型之前定义一个userSchema,如下所示:

const mongoose = require('mongoose')
const validator = require('validator')

const userSchema = new mongoose.Schema({ 
    name: {
        type: String,
        required: true, 
        trim: true
    }, 
    email: {
        type: String,
        require: true,
        trim: true, 
        lowercase: true,
        validate(value) {
            if(!validator.isEmail(value)) {
                throw new Error('Email is invalid')
            }
        }
    },
    age: {
        type: Number,
        default: 0,
        validate(value) {
            if(value < 0) {
                throw new Error('Age must be a positive number.')
            }
        }
    },
    password: {
        type: String,
        trim: true,
        lowercase: true,
        required: true,
        minlength: 7,
        validate(value) {
            if( value.toLowerCase().includes("password")) {
                throw new Error("Password can't be 'password'.")
            }
        }
    }
})

const User = mongoose.model('User', userSchema);
exports.User = User

Now it is a constructor, because we are saying each instance of User is a new instance of userSchema . 现在它是一个构造函数,因为我们说User每个实例都是userSchemanew实例。

I figured it out. 我想到了。 On the third in my index.js file, I left out require. 在index.js文件的第三部分,我省略了require。

Instead of this: 代替这个:

const User = ('./models/user')

It should have been this: 应该是这样的:

const User = require('./models/user')

Thanks for all your help, everyone! 谢谢大家的帮助!

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

相关问题 为什么我不断收到TypeError:args.sort不是函数? - Why do I keep getting a TypeError: args.sort is not a function? TypeError: res.sendStatus is not a function - 为什么我一直收到这个错误? - TypeError: res.sendStatus is not a function - Why do I keep getting this error? 为什么我不断收到此错误? 未捕获的类型错误:无法读取 null 的属性(读取“术语”) - why do i keep getting this error? Uncaught TypeError: Cannot read properties of null (reading 'term') 为什么我不断收到此错误? 未捕获的类型错误:无法读取 null 的属性“classList” - Why do I keep getting this error? Uncaught TypeError: Cannot read property 'classList' of null 为什么我在angularJS中一直得到undefined的TypeError设置属性? - Why I keep getting TypeError setting property of undefined in angularJS? 为什么我总是得到 Null? - Why do I keep getting Null? 为什么我不断收到ReferenceError:*未定义? - Why do I keep getting ReferenceError: * is not defined? 为什么我不断得到NaN? - Why Do I keep getting NaN? 为什么我不断得到$(...)。scrollSpy是未定义的? - Why do I keep getting $(…).scrollSpy is undefined? 获取 TypeError:使用 API 测试用户添加时,用户不是构造函数 - Getting TypeError: User is not a constructor when testing user add with API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM