這是我的 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]
}
但仍然得到同樣的錯誤。
uj5u.com熱心網友回復:
我不確定,但是每當您參考其他模型時,您總是必須使用 mongoose 參考關鍵字,然后使用該模型中的資訊來創建一個陣列。
uj5u.com熱心網友回復:
您的架構應該如下所示:
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;
帖子不需要型別宣告。
uj5u.com熱心網友回復:
你必須記住兩件事:
- 首先是因為您正在創建架構并且您沒有更改應用程式中的架構,因此不建議使用let。相反,請嘗試將您的架構存盤在Const變數中。
- “posts”是一個陣列,您可以簡單地將架構寫入陣列而不使用型別。此外,您必須在另一個架構上使用該架構。您可以使用以下方法更改代碼:
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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/410916.html
標籤:
下一篇:我嘗試從reactnative中的另一個js檔案匯入JS檔案中的陣列資料,并嘗試在reactnative中檢查陣列的長度
