Sails.js and Waterline: dynamic check on db query
I am using Sails 11.1 and Waterline 2.11.2 with MongoDB database.
I would like to validate the data inserted into my "Article" model using the validator in
for attribute 1. I used to work with lifecycle callbacks (especially beforeCreate
and beforeUpdate
), but it does double code.
Here you have a model truncated with just the appropriate attribute:
module.exports =
{
schema: true,
autoCreatedAt: false,
autoUpdatedAt: false,
attributes:
{
theme:
{
model: 'Theme',
required: true
}
}
}
I know how to define it statically:
in: ['something', 'something other']
I know how to call constants defined in a file constants.js
:
defaultsTo: function ()
{
return String(sails.config.constants.articleDefaultTheme);
}
But I would like to get all topics in my DB so that I can have dynamic checkout in
. So I wrote this:
theme:
{
model: 'Theme',
required: true,
in: function ()
{
Theme.find()
.exec(function (err, themes)
{
if (err)
{
return next({ error: 'DB error' });
}
else if (themes.length === 0)
{
return next({ error: 'themes not found' });
}
else
{
var theme_ids = [];
themes.forEach(function (theme, i)
{
theme_ids[i] = theme.theme_id;
});
return theme_ids;
}
});
}
}
But it doesn't work, I always get the error "1 sign is invalid". If I write them statically or if I test the method beforeCreate
with a different DB query, it works fine. If I sails.log()
return variable all topic tags are here.
I tried to return the JSON.stringify()
returned variable as well as in JSON.parse(JSON.stringify())
. I also tried converting theme.theme_id
as a string using a function String()
, but nothing else ...
What am I doing wrong? Or is it a mistake?
You can also check my question here: Waterline GitHub Issues
source to share
Configuring the models in scope attributes
in the field in
will of course throw an error because it shouldn't use the function, especially your function doesn't return anything, also if you force it to return something, it will return Promise
that Theme.find()...
did.
Try a different approach. There are Lifecycle Model Callbacks . You can use something like beforeCreate
or beforeValidate
to manually check the dynamic Theme
, if not valid return an error.
Or, if it's achievable using a standard DB relationship, just use a simple DB relationship.
source to share