Linked Questions

Popular Questions

How to add schema to another schema array?

Asked by At

I have address schema and customer schema. I have a field address array inside my customer schema. I will be sending an adress model as my req body and customer id as req param. How can I save that adress to adresses array which is declared inside customer schema?

This is my Customer Schema

const customerSchema = mongoose.Schema ({
  _id: mongoose.Schema.Types.ObjectId,
  name: String,
  phone_number: String,
  password: String,
  type:{type:String,enum:['admin','user']},
  adresses:['Adress'],
  orders:[{type: mongoose.Schema.Types.ObjectId, ref: 'Order'}]
});

This is my Adress Schema

const addressSchema= mongoose.Schema({
    _id:mongoose.Types.ObjectId,
    postalCode:Number,
    city:String,
    district:String,
    neighborhood:String,
    streetNumber:String,
    no:Number,
    buildingName:String,
    apartmentNumber:Number,
    floor:Number,
    coordinates:{
        latitude:Number,
        longitude:Number
    },
    addressName:String,
    customerId: {type: mongoose.Schema.Types.ObjectId,ref:'Customer'}


}); 

I could not figure out how am ı going to do this. I am finding the customer which I will going to push my address to like this.

This is how I get the specific customer

Customer.find({_id:req.params.customerId},(err,data)=>{
    if(err) return next(err);
    else{
      //What I am going to do here?
    }
});

First what type should I put inside the addresses array which is inside Customer Schema?

Second after finding the customer which I am going to add address to, what should I do? Mongoose 5.4.11 documentation was not enough for me. This link seemed what I needed but I did not figure out how to accomplish this problem.

https://mongoosejs.com/docs/subdocs.html

Related Questions