[英]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.