【问题标题】:Facing "throw new TypeError(`Invalid schema configuration: \`${name}\` is not ` +"面对“throw new TypeError(`Invalid schema configuration:\`${name}\` is not `+”
【发布时间】:2021-11-04 20:02:57
【问题描述】:

使用 Typescript 进入 NodeJS。所以主要问题是我正在尝试使用 Mongoose 遵循一对多文档结构。但正如问题所说,我面临这个问题:

throw new TypeError(`Invalid schema configuration: \`${name}\` is not ` +

TypeError: Invalid schema configuration: `Todo` is not a valid type at path `ref`

这是型号代码:


const Schema = mongoose.Schema;
const userSchema = new Schema({
    _id: Schema.Types.ObjectId,
    firstname: {
        type: String
    },
    lastName: {
        type: String,
    },
    email: {
        type: String,
        required: "Enter Email ID"
    },
    password: {
        type: String,
        required: "Enter Password"
    },
    todos: [
        {
            ref: 'Todo',
            _id: Schema.Types.ObjectId
        }
    ]
});

const todoSchema = new Schema({
    _id: Schema.Types.ObjectId,

    title: {
        type: String,
        required: "Enter a title"
    },
    createdAt: {
        type: Date,
        default: Date.now
    },
    content: {
        type: String
    }
})

export const Todo = mongoose.model('Todo', todoSchema);
export const User = mongoose.model('User', userSchema);

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    当你在一个模式中定义一个引用属性时,你只需要定义它的类型并提及它引用了哪个数据库模型

    类型应该是objectId

    架构应该是这样的

    const Schema = mongoose.Schema;
    const userSchema = new Schema({
        _id: Schema.Types.ObjectId,
        firstname: {
            type: String
        },
        lastName: {
            type: String,
        },
        email: {
            type: String,
            required: "Enter Email ID"
        },
        password: {
            type: String,
            required: "Enter Password"
        },
        todos: [
            {
                type: Schema.Types.ObjectId, // here is the issue
                ref: 'Todo'
            }
        ]
    });
    

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      这只是 Mohammed 解决方案的更简洁的解决方案。

      type 是定义架构时最重要的对象键,但您的待办事项字段缺少它。您需要像这样将type 设置为 ObjectId

      const Schema = mongoose.Schema;
      const userSchema = new Schema({
          ...
          todos: [
              {
                  type: Schema.Types.ObjectId, 
                  ref: 'Todo'
              }
          ]
      });

      【讨论】:

        猜你喜欢
        • 2020-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-16
        • 2022-10-22
        • 2022-01-06
        • 1970-01-01
        相关资源
        最近更新 更多