Search code examples
node.jsmongodbmongoosemongoose-schema

Missing 'street' and 'city' fields in Mongoose user document's 'address' sub-document


Why are the street and city fields not present in the address sub-document of a new user document created using Mongoose, despite being included in the addressSchema and provided when creating the document?

Here is my addressSchema:

const addressSchema = new Schema({
  address: {
    street: String,
    city: String
  }
});

here is my userSchema:

const userSchema = new Schema({
  name: String,
  age: Number,
  email: String,
  createdAt: Date,
  updatedAt: Date,
  bestFriend: mongoose.SchemaTypes.ObjectId,
  hobbies: [String],
  address: addressSchema,
})

And here is how I'm creating the new user document:

const user = await User.create({
  name: 'amal',
  age: 25,
  hobbies: ['weight lifting', 'Bowling'],
  address: {
    street: 'ernakulam',
    city: 'kochi'
  }
});

However, when I log the resulting document, it only contains an _id field for the address sub-document, and the street and city fields are not present.

What could be causing this issue, and how can I ensure that the street and city fields are included in the address sub-document when creating a new user document?


Solution

  • const userSchema = new Schema({
      name: String,
      age: Number,
      email: String,
      createdAt: Date,
      updatedAt: Date,
      bestFriend: mongoose.SchemaTypes.ObjectId,
      hobbies: [String],
      address: addressSchema,
    })
    

    => The address field should be the type of mongoose.Types.ObjectId,

    The address schema should be

    const AddressSchema = new mongoose.Schema ({
      street: String,
      city: String
    })
    

    In that way whenever you wanna get the address of a user you can populate the address field with .populate('address')