Home > Net >  Array of {key: value} in mongoose schema
Array of {key: value} in mongoose schema

Time:11-21

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"
    }
]

CodePudding user response:

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`

CodePudding user response:

Solution #1 Reference User Id

you can save the user ObjectId to the database then populate the id to show the name when you need it, if so, then you will need to reference the model that mongoose will populate from:

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

Solution #2 Embed user name

if you want to only save the user name, then the schema type will be String:

user: {
    type: String,
}

and you will save the user name to it whenever you create a new comment.

  • Related