0

I have a exemple data:

"_id" : ObjectId("5694ba11b3957b7ff69c4547"),
"name" : "Okas 1",
"job" : {
    "name" : "job try1",
    "_id" : ObjectId("5a6ff9f7a336e3bba40a1d5c")
},
"categories" : {
    "ss" : [ 
        {
            "name" : "10",
            "_id" : ObjectId("5a6ff9f7a336e3bba40a1d5c")
        }, 
        {
            "name" : "50",
            "_id" : ObjectId("5a6ff9f7a336e3bba40a1d5f")
        }
    ]
}

if I update with new data .

[{
   "name" : "800",
   "_id" : ObjectId("5a6ff9f7a336e3bba40a1d5a")
},
{
   "name" : "8",
   "_id" : ObjectId("5a6ff9f7a336e3bba40a1d5f")
}]

I should get the data

"_id" : ObjectId("5694ba11b3957b7ff69c4547"),
"name" : "Okas 1",
"job" : {
    "name" : "job try1",
    "_id" : ObjectId("5a6ff9f7a336e3bba40a1d5c")
},
"categories" : {
    "ss" : [ 
        {
            "name" : "10",
            "_id" : ObjectId("5a6ff9f7a336e3bba40a1d5c")
        }, 
        {
            "name" : "8",
            "_id" : ObjectId("5a6ff9f7a336e3bba40a1d5f")
        },    
        {
             "name" : "800",
             "_id" : ObjectId("5a6ff9f7a336e3bba40a1d5a")
        }
    ]
}

So I want to update if data exeist just update value but if not exist add new element in to array categories. I try but not working. the results are not appropriate

kyty
  • 76
  • 1
  • 9

1 Answers1

-1

You can do something like this:

model.findOne({_id:req.params.id}, (err, data) => {
  if (err) throw err;
  if(!data) {
      var newData = new model({
        name: req.body.name
        .....
  })
      newData.save((err, newdata) => {
         // Response
       })
  } else {
      data.name = req.body.name
     data.save((err, data) => {
         // Response
       })
  }
  
 

I hope this is what you want.

Merim
  • 1,283
  • 2
  • 21
  • 36
  • It's simple, you are looking for items by `findOne` mongoose method, then if you don't find item with the ID you create new item...I was also confused, I'm still a beginner, try to understand the principle, then use mongodb/mongoose docs to write the code. – Merim Feb 14 '18 at 07:21