首页 > 解决方案 > Mongoose 架构突然失效

问题描述

我目前正在开发一个 MERN 应用程序。我对后端和数据库相关主题相当陌生。

我已经使用以下模式配置了这个猫鼬模型:

item.model.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const itemSchema = new Schema({
    title: String, // String is shorthand for {type: String}
    author: String,
    body:   String,
    date: { type: Date, default: Date.now },
    meta: {
        reports: {type: Number, default: 0}
    }
});

const Item = mongoose.model('Item', itemSchema);

module.exports = Item;

在我的api.js文件中,这是我导入模型的方式:

const Item = require('../models/item.model');

现在,当启动我的服务器时,我收到以下错误:

TypeError: Invalid schema configuration: `String` is not a valid type at path `title`

我想知道为什么类型无效。我正在使用 mongoose 文档中的语法。我确实重构了我的代码并移动了我的后端文件夹。我无法想象这与错误有关,但是自从重构以来,就出现了这个错误。我还尝试将后端文件夹移回原来的位置,但仍然出现此错误。

标签: javascriptnode.jsmongooseschema

解决方案


您可以使用另一种方式进行类型定义

title: 'String'

或者

title: mongoose.Schema.Types.String


推荐阅读