How to add record to sailsjs through association using the Blueprint REST API - sails.js

I need to implement a through association in order to have a many-to-many relationship with a custom field in the join table. In SailsJS through associations require three models; two models are your business objects, Species and Lands in my case, and a third representing the join table SpeciesLands. See my SailsJS models at the bottom of this post.
Once I have the association set up how do I go about associating two objects through the blueprint API? Do I need to POST data to the /specieslands endpoint using the id of the Species and Land I want to link? Is it possible to create and link objects at the same time like you can with the many-to-many relationship? Is this something that needs to be done in a SailsJS controller rather than through the blueprint API?
Here are my models:
Species
module.exports = {
attributes: {
scientificName: {
type: 'string',
required: true,
unique: true
},
commonName: {
type: 'string'
},
taxon: {
type: 'string',
required: true
},
leadOffice: {
type: 'string'
},
lands: {
collection: 'lands',
via: 'land',
through: 'specieslands'
}
}
};
Lands
module.exports = {
attributes: {
agency: {
type: 'string',
required: true
},
name: {
type: 'string',
required: true,
unique: true
},
species: {
collection: 'species',
via: 'species',
through: 'specieslands'
}
}
};
SpeciesLands
module.exports = {
attributes: {
species: {
model: 'species'
},
land: {
model: 'lands'
},
population: {
type: 'string',
required: true,
enum: ['O', 'O+', 'P', 'U'] // THIS IS THE REASON FOR ASSOCIATION
}
}
};

I do not think it is possible like that.
I am pretty sure you have to:
Create Specie
Lands
Relation
1 & 2 using POST /modelName
3 using http://sailsjs.com/documentation/reference/blueprint-api/add-to

When using a through association, the Blueprint API will expect associations to be generated by POST into the associative model (The relation model).
In your case, if you wanted to associate an item from the Species model with an item from the Lands model, you would do something like this:
curl --header "Content-Type: application/json"
--request POST
--data '{species:15,land:51,population:"O"}'
http://www.example.com/SpeciesLands
Or in Postman:

Related

One way association with array of reference _id in sails js

I'm trying to use one way association because I need only to have reference from 1 model to other model but not vice versa.
Model Arts:
module.exports = {
attributes: {
fileName: {type: 'string', required: true},
softwareUsed: {
model: 'Softwares'
}
}
}
Model Softwares:
module.exports = {
attributes: {
name: {type: 'string', required: true}
}
}
This is my api:
http://localhost:1337/api/v1/arts/create
if this is my request body, it works fine:
request body:
{
"fileName": "booking.jpeg",
"softwareUsed": "5e70309cbf12b61299d6c528",
}
but i want to store array of softwareUsed, so i tried:
request body:
{
"fileName": "booking.jpeg",
"softwareUsed": ["5e70309cbf12b61299d6c528", "5e70309cbf12b61299d6c529"],
}
but i got an error with that:
error: OperationalError [UsageError]: Invalid new record.
Details:
Could not use specified `softwareUsed`. Expecting an id representing the associated record, or `null` to indicate there will be no associated record. But the specified value is not a valid `softwareUsed`. Instead of a string (the expected pk type), the provided value is: [ '5e70309cbf12b61299d6c528', '5e70309cbf12b61299d6c529' ]
I also tried to make it array in model:
softwareUsed: [{
model: 'Softwares'
}]
but still don't work.
Is there a way to that in one way association or I need to use other association, but how can I achieve that?
Thank you.
I think you need to label the softwareUsed attribute with a collection, not a model:
module.exports = {
attributes: {
fileName: {type: 'string', required: true},
softwareUsed: {
collection: 'Softwares'
}
}
}
All the documentation on one-to-many in the sails docs involves two-way associations and adding a via attribute, but I think this way works for a one-way association.
Of course, your first api call may now longer work: you may need to wrap the single software id in an array.

Create unique multikey index via model settings

I am using Sails v1.1 -
I created a many-to-many through custom model association following the sails doc here - https://sailsjs.com/documentation/concepts/models-and-orm/associations/through-associations
The PetUser model has two columns pet and user, where each is the respective id. I want to create a unique multi-key index, meaning there cannot be two rows with the same combination of "pet and user". Meaning the second call should succeed, and third call should fail with uniqueness error:
await PetUser.create({ user: 1, pet: 33 }); // should succeed
await PetUser.create({ user: 1, pet: 44 }); // should succeed as user/pet combination is different
await PetUser.create({ user: 1, pet: 33 }); // should fail
I tried adding unique: true to both the owner and pet attribute on PetUser model below, but only the first unique: true gets respected.
So this is my code in myApp/api/models/PetUser.js
module.exports = {
attributes: {
owner: {
model:'user',
unique: true
},
pet: {
model: 'pet',
unique: true
}
}
}
For implementing similar behavior I added a combined attribute and mark it unique. Also, I added beforeCreate and beforeUpdate model hooks on which I generate my combined attribute to check is it unique or not.
const YourModel = {
attributes: {
owner: {
model: 'user',
},
pet: {
model: 'pet',
},
petOwner: {
type: 'string',
unique: true,
}
},
beforeCreate : function(values,cb) {
// TODO get ids from related records or reset to default on missed relation record if you need it
const petId = 35;
const ownerId = 8;
values.petOwner = `${petId}-${ownerId}`;
cb();
},
beforeUpdate : function(values,cb) {
YourModel.beforeCreate(values, cb)
},
};
module.exports = YourModel;
In result when you tries to add the record with the same relations, you will get E_UNIQUE as you expected.

Sails.js populate with where

I need to select users with dogs (pets with type equal 'dog')
var User = Waterline.Collection.extend({
identity: 'user',
attributes: {
firstName: 'string',
lastName: 'string',
pets: {
collection: 'pet',
via: 'owner'
}
}
});
var Pet = Waterline.Collection.extend({
identity: 'pet',
attributes: {
type: 'string',
name: 'string',
owner: {
model: 'user'
}
}
});
I didn't find any examples, I tried like this
User.find().populate('pets', {type: 'dog'}).exec(err, users) ...
and this
User.find().where({'pets.type': 'dog'}).populate('pets').exec(err, users) ...
but that does not work
Would be greate if result users array will has no pets records
Did you try this?
User.find().populate('pets', {
where: {
type: 'dog'
}
}).exec(err, users)...
If you don't need to query users and just need the query for dogs. You could just as easily reverse the query.
Pet.find({type: 'dog'}).populate('users').exec(err, petsWithUsers)
What you are looking for hasn't been implemented in waterline (Sails ORM) yet, check issue #266 for more details.
User.find().populate('pets', {type: 'dog'}).exec(err, users) ...
This will return all users (User.find()) and only populate pets of type dog (populate('pets', {type: 'dog'})). So you'll have users without dogs in your results.
User.find().where({'pets.type': 'dog'}).populate('pets').exec(err, users) ...
Waterline does not support dot (.) notation. Sails-mongo does have some support for it due to MongoDB support.
Finally, if you are using one of the SQL adapters you may work around this by doing a raw sql query using .query() (docs).

sailsjs / waterline query "where" not empty

Hy there,
Before going to the hacky / cutom way i wanted to know if there is a built in query way to check for an empty / non empty many to many relationship as i was not successfull neither on google nor the doc.
If i take the example in the doc let's imagine i want to retrive a user only if he has a a Pet or Retrive a Pet without any Owner through a query.
// A user may have many pets
var User = Waterline.Collection.extend({
identity: 'user',
connection: 'local-postgresql',
attributes: {
firstName: 'string',
lastName: 'string',
// Add a reference to Pet
pets: {
collection: 'pet',
via: 'owners',
dominant: true
}
}
});
// A pet may have many owners
var Pet = Waterline.Collection.extend({
identity: 'pet',
connection: 'local-postgresql',
attributes: {
breed: 'string',
type: 'string',
name: 'string',
// Add a reference to User
owners: {
collection: 'user',
via: 'pets'
}
}
});
P.s. i know how to filter results after query execution that's not what i'm asking :)
There is nothing built in (aka User.hasPet() ) or something like that., so the simple answer is NO
If I know of these issues before hand I tend to write my DB in such a way that the queries are fast. IE: the User schema would have a hasPets column. Whenever a pet is added/removed a callbacks hits the user table to mark that field if it has an owner or not. So then I can query User.findAll({hasPet:true}).
Its a little much, but it depends on where you speed is needed.
This is a bit late, but I wanted to let you know it's pretty easy to do this with the Waterline ORM lifecycle functions. I've done it in a few of my projects. Basically, use the beforeCreate and beforeUpdate functions to set your flags. For your user, it might look like...
var User = Waterline.Collection.extend({
identity: 'user',
connection: 'local-postgresql',
beforeCreate: function(values, next) {
if (values.pets) {
values.has_pet = true;
} else {
values.has_pet = false;
}
next();
}
beforeUpdate: function(values, next) {
if (values.pets) {
values.has_pet = true;
} else {
values.has_pet = false;
}
next();
}
attributes: {
firstName: 'string',
lastName: 'string',
// Add a reference to Pet
pets: {
collection: 'pet',
via: 'owners',
dominant: true
},
has_pet: {
type: 'boolean'
}
}
});
Then you can query based on the has_pet attribute

Remove undesirable fields from being returned in sails

I am new to SailsJS and stuck in Data Model as follows:
I have a User model as follows:
module.exports = {
attributes: {
firstName: {
type: 'string'
},
email: {
type: 'email',
required: true
},
password: {
type: 'String'
},
passwordSalt: {
type: 'String'
},
projects:{
collection: 'ProjectMember',
via: 'userId'
}
}
};
Task Model :
module.exports = {
taskName: {
type: 'String'
},
userId: {
model: 'User'
}
};
In Task model, it is getting all fields from User table which is not required while task data is rendered. I was planning to create one more model called TinyUser which stores only required fields to be shown when task data is rendered.
But TinyUser should just refer User table and get required data from it rather than we creating all data for TinyUser manually when user data is created.
Is there any way this can be achieved in Sails?
Thanks in Advance..
I'm not sure about your question, but this will return a list of required attributes for any model
_.find(sails.models.<YOUR MODEL>._attributes, function(attr){return attr.required})
If your intent it to simply remove undesirable fields you can override the toJSON / toObject methods
see
https://github.com/balderdashy/waterline-docs/blob/master/models.md#toobjecttojson-instance-methods
User.find({select:['firstName', 'email']}).exec()