Mongoose schema nested object

Hello, this is my code:

const NewUserSchema = mongoose.Schema({
    name:{type:String, required:true},
    password:{type:String, required:true},
    email:{type:String, required:true},
    friends: {type:Array, default: undefined},
    posts:{type:Object, default: {}}

})

How can I create a different schema for posts property? I want it to receive several properties, such as head,body,image and so on

Wouldn’t you want posts to be an array instead of an object?

Then you could do something like:

const NewUserSchema = mongoose.Schema({
    name:{type:String, required:true},
    password:{type:String, required:true},
    email:{type:String, required:true},
    friends: {type:Array, default: undefined},
    posts: [{
      head: { 
        type: String 
      },
      body: { 
        type: String 
      },
      image: { 
        type: String 
      }
    }]
})
1 Like

Actually no, I wanted posts to be an array of objects where each object would be a single post that contains those properties

I believe the code I posted above does make posts an array of objects wit the three properties you mentioned. I did not test the code, so I could be mistaken.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.