comments我的界面和架構中有一個欄位,如下所示
export interface Blog extends Document {
...
comments: { user: ObjectId; comment: string }[]
...
}
const blogSchema = new Schema<Blog>({
...
comments: [
{
user: {
type: ObjectId
},
comment: {
type: String
}
}
],
...
})
但是,架構會引發此錯誤'ObjectId' only refers to a type but is being used as a value here.。我知道模式的撰寫方式有點奇怪,但我對如何改進感到困惑。
我想要在資料庫中的東西是這樣的
[
{
user: "Vivid",
comment: "Vivid's comment"
},
{
user: "David",
comment: "David's comment"
}
]
uj5u.com熱心網友回復:
我相信你需要改變ObjectId,以
mongoose.Schema.Types.ObjectId
要么,要么你可以做這樣的事情:
const mongoose = require('mongoose');
// ... other imports
const { ObjectId } = mongoose.Schema.Types;
// ... now use in code as `ObjectId`
uj5u.com熱心網友回復:
解決方案 #1參考用戶 ID
您可以將用戶 ObjectId 保存到資料庫中,然后在需要時填充 id 以顯示名稱,如果是這樣,那么您將需要參考 mongoose 將從中填充的模型:
user: {
type: ObjectId,
ref: 'UserModel'
}
解決方案#2嵌入用戶名
如果您只想保存用戶名,那么架構型別將為字串:
user: {
type: String,
}
并且每當您創建新評論時,您都會將用戶名保存到其中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/361888.html
標籤:javascript 节点.js 打字稿 MongoDB 猫鼬
