VIVID
VIVID

Reputation: 585

Array of {key: value} in mongoose schema

I have a comments field in my interface and schema as follows

export interface Blog extends Document {
    ...
    comments: { user: ObjectId; comment: string }[]
    ...
}


const blogSchema = new Schema<Blog>({
    ...
    comments: [
        {
            user: {
                type: ObjectId
            },
            comment: {
                type: String
            }
        }
    ],
    ...
})

However, schema throws this error 'ObjectId' only refers to a type but is being used as a value here.. I know that schema is written kind of in a weird way, but I'm confused with how to improve.

What I want in database is something like

[
    {
        user: "Vivid",
        comment: "Vivid's comment"
    },
    {
        user: "David",
        comment: "David's comment"
    }
]

Upvotes: 0

Views: 521

Answers (1)

Matt Oestreich
Matt Oestreich

Reputation: 8528

I believe you need to change ObjectId to

mongoose.Schema.Types.ObjectId

Either that, or you could do something like:

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

Upvotes: 1

Related Questions