skip to Main Content

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?

2

Answers


  1. Your address schema should be like this:

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

    Otherwise the street and city properties would be at user.address.address.street and user.address.address.city.

    Login or Signup to reply.
  2. 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')

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search