Reputation: 2019
I am new to Sails and facing a small issue with models.
I have defined a user model as follows:
module.exports = {
attributes: {
firstName: {
type: 'string'
},
lastName: {
type: 'string'
},
email: {
type: 'email',
required: true
},
password: {
type: 'String'
},
passwordSalt: {
type: 'String'
},
projects:{
collection: 'ProjectMember',
via: 'userId'
}
}
};
I have one more model called Plan which has user as its foreign key:
module.exports = {
planId: { type: 'string'},
userId: { model: 'User'}
};
Now Plan stores all user data. Is there any way I can restrict Plan model to hold only some of User details like firstName, lastName, email and projectMembers instead of storing other personal info. like password, passwordSalt, etc?
Thanks In Advance
Upvotes: 0
Views: 68
Reputation: 86
Plan model will not store User data. It will only store the data values defined in its schema i.e planId and userId. If you want to return back only some user details then you can do this :
In Plan model :
First define a toApi method in model:
module.exports = {
attributes : {
planId: { type: 'string'},
userId: { model: 'User'},
toApi :toApi
}
};
function toAPi(){
var plan = this.toObject();
return {
firstName : plan.userId.firstName,
lastName : plan.userId.lastName,
email : plan.userId.email,
projectMembers : plan.userId.projectMembers
};
}
and then in a method, do this :
function getUserData(){
Plan
.find()
.populate('userId')
.then(function(data){
return data;
})
}
In your plan controller, do this :
Plan
.getUserData()
.then(function(userData){
return res.ok(userData.toApi());
})
Upvotes: 1
Reputation: 5979
Plan is not storing User data, it is only storing a reference to the user data found in the User model.
Upvotes: 1