【问题标题】:Mongoose TypeError: Schema is not a constructor I've tried solutions from other posts but no workMongoose TypeError: Schema is not a constructor 我已经尝试过其他帖子的解决方案但没有工作
【发布时间】:2019-10-24 02:09:42
【问题描述】:

我正在练习 React.js 和 MongoDb,我尝试使用 Mongoose 保存一些数据,但它一直返回 TypeError: Schema is not a constructor。

我使用 Postman 进行了测试,而不是通过带有 React.js 的浏览器。

我查看了许多类似的 Stackoverflow 帖子,但无法弄清楚为什么我的代码不起作用。

这是我的 Schema 代码:

const mongoose = require("mongoose");

const ContactSchema = mongoose.Schema({
  name: String,
  number: Number
});

module.exports = mongoose.model("ContactData", ContactSchema);

这是我的 POST 请求:

router.post("/create_contact", (req, res) => {
  const { name, number } = req.body

  let contact = new ContactData(
    name,
    number
  );

  contact.save((error, contact) => {
    if (error) {
      return console.error(error);
    }

    return res.json(contact);
  });
});

没有发现连接到本地 MongoDb 和运行 Express 服务器的问题。

我在这里缺少什么?任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: node.js mongoose schema


    【解决方案1】:

    您需要在实例化新架构时使用 new 关键字:

    const ContactSchema = new mongoose.Schema({
      name: String,
      number: Number
    });
    

    我希望这会有所帮助。

    【讨论】:

    • 这可能是一个愚蠢的问题,但是,您是否在路由文件中导入了 ContactData 模型?
    • 我也试过这个,但仍然得到错误。 @vitomadio 是的,我有。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2019-07-15
    • 2018-05-24
    • 2020-05-28
    • 2020-08-25
    相关资源
    最近更新 更多