0

This is how my Mongoose db looks like

_id: ObjectId("5c7d6b0b54795c02a6a5cb16")
people:[
   {
   _id: ObjectId('7c7d6b0b54795c02a6aa878')
   name: John
   bizs:[
      {name:"Shop A"},
      {name:"Shop B"}
    ]
  },
  {
   _id: ObjectId('7c7d6b0b54795c02638b9cd')
   name: Mary
   bizs:[
      {name:"Shop X"}
    ]
  }
]

If I add a person who is already in the database (say for example John) with his business, I need the business to append itself in the bizs array. Eg Shop A,ShopB, Shop C.

But if I add another person who is not in the database (like how I have added Mary) I need it to create a whole new object in the people array.

I have tried doing this with upsert but it does'nt give me what I want.

How do I get something like this?

1 Answers1

0

You first need to find if there exist a person with name "John"(as per your example),this can be done using a simple find query.if the result of that query is null or undefined then you can insert a new object(a new record into people array) else you can append it to the found document and the save it.

const name =  req.body.name;
Schema.findOne({"people.name" : name} , (err , user)=>{
    if(err){
        //handle
    }

    if(!user){
        //create a new record and push it to people array and save it.
    }
    else{
        //create a record(with your object) and push it to people array and save
        user.people.push();
        user.save()

    }
});
Mahendra suthar
  • 401
  • 5
  • 18
  • Isn't there any 'Out of the box' way to do this in mongodb/mongoose instead of first finding and inserting if not found as how you have suggested? – Amani Huruma Mar 18 '19 at 16:36
  • there's no 'out of box solution' for this one.But i hope this will help you out : https://stackoverflow.com/questions/40102372/find-one-or-create-with-mongoose – Mahendra suthar Mar 19 '19 at 13:27