繁体   English   中英

mongoose 模式中的 {key: value} 数组

[英]Array of {key: value} in mongoose schema

我的界面和架构中有一个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"
    }
]

我相信您需要将ObjectId更改为

mongoose.Schema.Types.ObjectId

要么,要么你可以做类似的事情:

const mongoose = require('mongoose');
// ... other imports
const { ObjectId } = mongoose.Schema.Types;
// ... now use in code as `ObjectId`

解决方案 #1参考用户 ID

您可以将用户 ObjectId 保存到数据库,然后填充 id 以在需要时显示名称,如果是这样,那么您将需要引用 mongoose 将从中填充的 model:

user: {
    type: ObjectId,
    ref: 'UserModel'
}

解决方案 #2嵌入用户名

如果您只想保存用户名,则架构类型将为字符串:

user: {
    type: String,
}

并且每当您创建新评论时,您都会将用户名保存到其中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM