首页 > 解决方案 > 面对“throw new TypeError(`Invalid schema configuration:\`${name}\` is not `+”

问题描述

使用 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.jsmongodbmongoose

解决方案


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

type是定义架构时最重要的对象键,并且您的 todo 字段缺少它。您需要type像这样设置为 ObjectId

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


推荐阅读