0

Mongoose Restaurant Schema

const mongoose=require('mongoose');    

const RestaurantSchema=mongoose.Schema(
    {
        _id:{type:mongoose.Schema.Types.ObjectId,required:true},
        restaurantName:{type:String,required:true},
        phone:{type:String,required:true},       

        offer: [{type:mongoose.Schema.Types.ObjectId,ref:"Offer"}]
            
    });

module.exports=mongoose.model("Restaurant",RestaurantSchema);

Updating method

Restaurant.findByIdAndUpdate(userid, { offer:[ "offerObjectId" ]},
                    function (err, docs) {
                        if (err) {
                            console.log(''+err);
                            res.status(500).json({
                                messahe:err
                            });
                        }
                        else {
                            console.log("restaurant : ", docs);
                            res.status(201).json({
                                messahe:docs
                            });
                        }
                    });

while i using above method to update new offer, that's overwriting previous offers in array data, But I want to keep my previous data, while i updating new offer, How can i achieve that?

FGH
  • 2,900
  • 6
  • 26
  • 59
  • 1
    use `$push` operator to add element in array `{ $push: { offer: "offerObjectId" } }` – turivishal Jun 20 '21 at 06:31
  • Thanks man,**it's working well**, can you update as an answer, i will accept it – FGH Jun 20 '21 at 06:38
  • there are many duplicate questions and when we just search in google "how to push element in array in mongodb?" you will get lots of helpful resources. – turivishal Jun 20 '21 at 06:45
  • 1
    Does this answer your question? [Push items into mongo array via mongoose](https://stackoverflow.com/questions/33049707/push-items-into-mongo-array-via-mongoose) – turivishal Jun 20 '21 at 06:45
  • no, i searched but i was not found – FGH Jun 20 '21 at 07:03

0 Answers0