const getMe = await UserModel.scope("test").findOne({
where: {
uid: uid,
},
include: [
{
model: GroupModel,
as: "groups",
include: ["product"],
},
],
});
I am trying to manage excluding fields and allowing fields based on scope.
defaultScope: {
attributes: {
exclude: ["id"],
},
},
scopes: {
test: {
atrributes: {
exclude: ["email"],
},
},
},
associations
UserModel.hasMany(GroupModel, { as: "groups" });
Groupmodel.belongsTo(UserModel, {
foreignKey: "userId",
as: "user",
});
GroupModel.belongsTo(ProductModel, {
foreignKey: "productId",
as: "product",
});
As a test I am by default excluding "id", and with the test scope I am excluding "email". I have tried everything from exclude include setting attributes directly in the findOne call. Nothing works.
What is the proper way to exclude certain fields say for "Public" returns, and include all fields for an "Admin scope" of some sort?
CodePudding user response:
If you have defaultScope like this.
defaultScope: {
attributes: {
exclude: ['email']
}
}
When you do find query, it excludes "email" by default and use unscoped to disable the defaultScope.
// This should not return email
UserModel.findOne()
// Admin case: unscoped to disable defaultScope. This should return email.
UserModel.unscoped().findOne()
Alternatively, if you would like to be more explicit, you can have scope named "admin".
{
defaultScope: {
attributes: {
exclude: ['email']
}
},
scopes: {
admin: {} // No special options for admin scope. No exclusion.
}
}
This way when you do find query, it is excluding "email" by default. Then, if you use "admin" scope, it won't exclude anything.
// This should not return email
UserModel.findOne()
// Admin case: This should overwrite the defaultScope.
UserModel.scope('admin').findOne()
.scope(str) function overwrites the defaultScope, so any options in defaultScope is ignored when you use .scope(str).
