Search code examples
sails.jswaterline

Waterline: Create or update a populate record


My question is basic but I can not find an answer in the documentation. I have two models: 'Person' and 'Location' being associated One-to-one. I want to create or update 'populated child records' in the Location collection.

 let person = await Person.findOne({ phone: inputs.phone }).populate('reside');

Well return

{ reside: [],
createdAt: 1540081110195,
updatedAt: 1540331824622,
id: '5bcbc5d609618e2cfbe64883',
phone: '+42424242',}

I want to create new location record (when they do not exist) or update if their exist. I try

let location = await Location.update({ id: person.reside.id })
.set({city: inputs.city,
    street: inputs.street,
  }).fetch;

But it does not work when no record has been created yet.

model/Person.js

phone: {
  type: 'string',
  unique: true,
},
reside: {
  collection:'location',
  via: 'owner'
},

models/Location.js

city: { type: 'string' },
street: { type: 'string' },
owner:{
  model:'person',
  unique: true
}

I use action2


Solution

  • I finally found here methods .addToCollection(), .removeFromCollection(), or .replaceCollection() to modify the populated values of a particular record or set of records. It does not seem to be the most appropriate place in the doc to talk about it