面对"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);

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

类型应为 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'
}
]
});

希望对您有所帮助

这只是穆罕默德解决方案的一个更简洁的解决方案。

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

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

相关内容

最新更新