[英]Getting invalid schema error, when having array of mongoose schema objects
这是我的 userPost.js 架构:
const mongoose = require("mongoose");
let userPostSchema = new mongoose.Schema({
id:{
type: mongoose.Types.ObjectId
},
body:{
type: String
}
}, {timestamps: true});
const UserPost = mongoose.model("post", userPostSchema);
module.exports = UserPost;
这是我的 userAccount.js 架构:
const userPost = require("./UserPost");
const mongoose = require("mongoose");
let userAccountSchema = new mongoose.Schema({
id:{
type: mongoose.Types.ObjectId
},
name:{
type: String
},
posts:
{
type: [userPost]
}
}, {timestamps: true});
let userAccount = mongoose.model("account", userAccountSchema);
module.exports = userAccount;
我收到帖子错误:
node_modules\mongoose\lib\schema.js:984
throw new TypeError('Invalid schema configuration: ' +
^
TypeError: Invalid schema configuration: `model` is not a valid type within the array `posts`.See http://.../mongoose-schematypes for a list of valid schema types.
at Schema.interpretAsType (C:\Users\BackEnd\node_modules\mongoose\lib\schema.js:984:15)
at Schema.path (C:\Users\BackEnd\node_modules\mongoose\lib\schema.js:677:27)
at Schema.add (C:\Users\BackEnd\node_modules\mongoose\lib\schema.js:495:12)
我在 userAccount.js 中使用了 2 个模式 userPost.js。 问题是什么?
为什么我会收到以下错误:
TypeError:无效的架构配置: model
不是数组posts
中的有效类型
我尝试咨询以下链接,尤其是 Mongoose 官方文档的第三个代码摘录: https://mongoosejs.com/docs/schematypes.html#arrays
我更改了以下代码:
posts:[
{
type: userPost
}
]
至:
posts:
{
type: [userPost]
}
但仍然得到同样的错误。
您的架构应该如下所示:
const userPost = require("./UserPost");
const mongoose = require("mongoose");
let userAccountSchema = new mongoose.Schema({
id:{
type: mongoose.Types.ObjectId
},
name:{
type: String
},
posts: [userPost]
}, {timestamps: true});
let userAccount = mongoose.model("account", userAccountSchema);
module.exports = userAccount;
帖子不需要类型声明。
你必须记住两件事:
const mongoose = require("mongoose"); export const userPostSchema = new mongoose.Schema({ id:{ type: mongoose.Types.ObjectId }, body:{ type: String } }, {timestamps: true}); const UserPost = mongoose.model("post", userPostSchema); module.exports = UserPost;
接着:
import {userPostSchema} from "./UserPost"; const mongoose = require("mongoose"); const userAccountSchema = new mongoose.Schema({ id:{ type: mongoose.Types.ObjectId }, name:{ type: String }, posts: [userPostSchema] }, {timestamps: true}); let userAccount = mongoose.model("account", userAccountSchema); module.exports = userAccount;
我不确定,但每当您引用其他 model 时,您总是必须使用 mongoose 参考关键字,然后使用来自该 model 的信息来创建数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.