Monday 10 April 2017

Update ObjectId while saving another object

Am trying to update the the objectId of a foreign key in my schema after saving

   router.post('/add/:id', (req,res)=>{
    const newMenu = new Menu()
    newMenu.menu_name = req.body.menu_name

    const restaurantId = req.params.id

    Menu.addNewMenu(newMenu, (err, menu)=>{
      if (err) {
        console.log(err);
        res.json({status: false, err: err})
      }else {
        Restaurant.findRestById(restaurantId,(err,restaurant)=>{
          restaurant.update({
            $push: {menus: menu._id}
          })
          restaurant.save((err,rest)=>{
            res.json({status: true})
          })
        })
      }
    })
  })

But after this menus array doesn't get updated

this is my Menu Schema

    const MenuSchema = mongoose.Schema({
  menu_name:{
    type: String,
    required: true
  },
  items:[
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Item'
    }
  ]
})

And Restaurant Schema

    const RestaurantSchema = mongoose.Schema({
  rest_name: {
    type: String,
    required: true
  },
  opening_period:{
    type: String,
    required: true
  },
  image_url:{
    type:String,
    required: true
  },
  menus:[
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Menu'
    }
  ]
})



via Sagaya Adols

No comments:

Post a Comment