Search code examples
node.jssails.jswaterlinesails-orientdb

Add new Document into field type Json through Waterline


I am trying to add a new document or you can say a new key value pair to an existing json type field, but it is replacing the older key value pair e.g. before my embedded field was {"@type":"d","key1":"example1"} and when I executed the update call

WL_MODELS.numbers.update({id: req.body.SID},{numbers: {"key2":"example2"}},function(err,model){ if(err) console.log(err); else {  console.log(model);}} ); 

it replaces the value of numbers: {"@type":"d","key2":"example2"} but i want to add the new key value pair inside the existing embedded or json document, if my method is wrong then tell me how can i do it using waterline and sails-orientdb?


Solution

  • xeeB, in waterline json is a datatype just like integer or string and similarly to those you can't perform nested operations against it. In other words, doing .update(criteria, { attribute: json }) will replace the whole json object which is what you are experiencing.

    To achieve what you want you'll first need to get the json, before changing it, for example:

    WL_MODELS.numbers.findOne({id: req.body.SID}, function(err, model){
      model.numbers["key2"] = "example2";
      model.save(function(err){
        console.log("saved:", model);
      });
    });
    

    Let me know if that doesn't work.