【问题标题】:How to avoid 'X' is not a constructor error in node.js?如何避免'X'不是node.js中的构造函数错误?
【发布时间】:2020-09-27 17:07:20
【问题描述】:

我正在使用 node 和 mongo 创建一个 RESTApi,并且在将数据保存到 mongo 时,我得到了一个 not a constructor 错误。我不知道我为什么会得到这个。

const mongoose= require('mongoose');

const postSchema = mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    date: {
        type: Date,
        default: Date.now
    },
})

module.exports= mongoose.model('Posts',postSchema);

现在,这是我的路线文件:

const express= require('express');
const router= express.Router();
const userpost= require('../model/post')

router.get('/', (req, res) => {
    res.send('Hey Thats a post')
})

router.get('/specific',(req,res)=>{
    res.send('specific post')
})

router.post('/',(req,res)=>{
    console.log(req.body.title)
    const Post= new userpost({
        title: req.body.title,
        description: req.body.description,
    })
    Post.save().then(data=>{
        res.json(data);
    })
})

module.exports=router;

在我尝试使用 Post 请求后,我收到一条错误消息,提示 userpost 不是构造函数。

TypeError: userpost 不是构造函数 在 E:\docs\node\routes\posts.js:15:17

【问题讨论】:

  • console.log(userpost) 看看结果如何
  • 如果我在新的 userpost 初始化之前登录,它显示空 json '{}',如果我在初始化之后这样做,它显示构造函数错误

标签: javascript node.js api express constructor


【解决方案1】:

当你创建新的 Schema 时,你必须使用 new 关键字。

const postSchema = new mongoose.Schema({
   //attributes
})

Schemas

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-09
  • 1970-01-01
  • 2017-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-25
相关资源
最近更新 更多