Home > Software design >  How can I add custom keys to to mongoose schema item?
How can I add custom keys to to mongoose schema item?

Time:09-29

I have a simple mongoose schema for a post:

const postSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true,
        unique: true
    },

    body: {
        type: String,
        required: true,
        unique: false
    }
})

And I would like to add a custom key to each item called interface, that I could later use in a automatically generated post creation page.

Like this

const postSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true,
        unique: true,
        interface: '<input type="text" name="title">'
    },
    
    body: {
        type: String,
        required: true,
        unique: false
        interface: '<textarea name="body">...</textarea>'
    }
})

But after creating a post with this schema and accesing this is the result.

{
  _id: new ObjectId("6151f2bbf678e03c1b2f609c"),
  title: 'a post',
  body: 'body...',
  __v: 0
}

How do I acceses the interface key of each property? like: post.title.interface

CodePudding user response:

If we look at the line that's causing your error we can see that JS thinkgs you're trying to assign multiple strings with a random unknown keyword in between. interface: "<input type="text" name="title">"

Those double quotes come in pairs, using a double quote will open a string that's then closed by the next double quote. The simplest fix is to wrap the whole string inside on single quotes like so. interface: '"<input type="text" name="title">"'

  • Related