Waterline defaultsTo not setting the value before inserting into db - javascript

The title is pretty straight forward. I have an attribute which looks like this:
isSet: {
type: boolean,
defaultsTo: false
}
So my goal is to have the value set to false everytime a user is created. But when I do create a user this value is null/undefined
The only workaround I found is to set the values in the beforeCreate method

Type should be string. This should work:
isSet: {
type: 'boolean',
defaultsTo: false
}

Related

Prisma/React Query Dependent undefined type challenges

I would like to take the output of one query (a TRPC query on Prisma) and use this as the dependent input in a future query.
I followed the dependent documentation for React Query but running into type errors that the return of the first may possibly be undefined (e.g. product is possibly 'undefined'):
const { data: product } = api.product.getUnique.useQuery({ id: pid });
const options = api.option.getAll.useQuery(
{
product: product.productSize,
region: product.productRegion,
},
{ enabled: !!product }
);
Does the inclusion of enabled not already handle this? If not, what is the correct way to adapt for Typescript.
Just casting the product value as a boolean return any truthy value (f.e if product will be equal to {} it will still result in true, that means that product won't necessarily have the productSize or productRegion properties, I would change it first to:
{ enabled: !!product && product.productSize && product.productRegion }
If that doesn't fix the typescript error, you as a developer can know for sure that the values are actually there so what you can use the as keyword in typescript to tell it that you know for sure that the type is what you want it to be:
(In this example I assumed that the values are string but you can change it to number or whatever the true value of them are)
const options = api.option.getAll.useQuery(
{
product: product.productSize as string,
region: product.productRegion as string,
},
{ enabled: !!product && product.productSize && product.productRegion }
);

Ajv library: Accessing keys in the nested schema validation javascript

I'm working on the use case where I need to validate the schema using ajv lib of the provided data which can be nested.
Now the problem is, Schema could change based on the value of a particular variable, which is not in the scope where this check is to be done.
how do I achieve it through ajv.
I tried using if-else & data & const but no luck.
I've recently encountered similar use case with ajv validator.
By looking at your issue I believe you need to access some other scope of the actual object passed for validation, In my case it was lying in the root of the object.
So I used the validate function in ajv's User Defined Keyword section, which in turn is giving me the whole object from top level in the first index of arguments itself, that way I accessed my dependent key in validate function and used it in my ajv IF: condition, eg
ajv.addKeyword({
keyword: "isRegular",
validate: (...test) => {
const test1 = test[1]
return test1.dependentKeyFromRootOfObject === "REGULAR"
},
})
and used the then created keyword isRegular in the nested object's IF: condition like
if: { isRegular: true },
then: {
properties: {
rcType: { type: "string" },
date: { type: "string" },
},
required: ["rcType", "date"],
additionalProperties: false,
},
else: {
properties: {
rcType: { type: "string" },
},
required: ["rcType"],
additionalProperties: false,
},
Hope this helps.

In sails, how to handle "nulls" in a JSON field in a database?

Well say I have a database that has a schema like:
CREATE TABLE public.mytable
(
datacolumn json,
id serial NOT NULL,
PRIMARY KEY (id)
)
Clearly datacolumn can be null: null is even an important value of this.
Now in sails I have a datamodel defined as:
moduel.exports = {
attributes: {
datacolumn: {
type: 'ref',
columnType: 'json',
allowNull: true,
},
},
id: {
type: 'number',
},
}
This should work right? - Well it doesn't sails refuses to lift:
Failed to lift app: userError: The attribute datacolumn on the mytable model contains invalid properties. The allowNull flag may not be used on attributes with type json or type ref.
I could of course just remove the line allowNull: but that would give lots of warnings that null is not a valid value (directly logged, and giving like 10 lines per warning). And I doubt it will correctly insert null values would it?
So how to handle above database schema?

Mongoose saving empty array error "TypeError: Cannot read property '1' of null"

I have a schema that is defined like so:
const userSchema = new Schema({
...
surveys: [surveyKeySchema],
...
})
Where surveyKeySchema is actually a subdocument scheme defined like so:
const surveyKeySchema = new Schema({
slug: {
type: String,
required: 'Please supply a slug',
unique: true,
lowercase: true,
trim: true
},
name: {
type: String,
required: 'Please supply a name',
trim: true
},
responseCount: {
type: Number,
default: 0
}
})
Now whenever I try to modify anything on the user except for this array, everything goes fine. When instantiating the user, it is also totally fine. I can also call await user.save() in my code right before I empty the array.
It's also fine when I remove any subdocument from the survey as long as there is at least 1 element remaining.
However, when I try to remove the final subdocument using:
await user.surveys.id(sid).remove()
await user.save()
I get an error on the .save() which is just TypeError: Cannot read property '1' of null. I'm confused and can't find anything about this online, I assume it must be requiring at least one subdocument to be present? Is there any way to remove this, or if my assumption is wrong how would I go about resolving this?
Thanks in advance! And my apologies if I'm missing something obvious!
EDIT:
I found that mongoose's mongo error handler was actually throwing this in a regex it was using to parse the error message. Hacking this around to return the raw error message:
E11000 duplicate key error index: db.users.$surveys.slug_1 dup key: { : null }
As per this question I tried adding sparse: true but this didn't work.
For anyone else having this issue, here's what I did:
In node_modules/mongoose-mongodb-errors/lib/plugin.js on line 19, add a simple console.error(err.message) so you can actually get the output and not the regex handler error.
Because when you save an empty array of subdocuments in Mongoose it is equivalent to having the subschema set to values of null, this means that when Mongoose evaluates the indices of your subdocument collection it will evaluate it as having a value of null for each property. If you're indexing with a property (i.e. one of the properties in your subdocument schema has unique: true on it) then this is a violation as a null value cannot be unique, at least not in Mongo world. To get around this you can add sparse: true.
Any documents in the existing collection and the existing collection itself will create an issue with now having a changed index. You need to drop the index for this to work. I dropped the entire collection because I didn't need it anyways.
Here's my updated schema:
const surveyKeySchema = new Schema({
slug: {
type: String,
required: 'Please supply a slug',
unique: true,
lowercase: true,
sparse: true,
trim: true
},
name: {
type: String,
required: 'Please supply a name',
trim: true
},
responseCount: {
type: Number,
default: 0
}
})

Mongoose: how to prevent null values being added to array of ObjectId

Title says it all. Below is a schema property definition that I thought would work, but doesn't do the job. I figured required: true on the type object should work?
users: {
type: [
{
type: Schema.Types.ObjectId,
ref: 'User',
required: true
}
],
default: []
}
the following query allows a null value to be added to the array:
MyModel.findByIdAndUpdate(id, {$addToSet: {users: ['']}})
aaaaaaaand, of course as soon as I post to SO, i find the answer for myself. need to set option runValidators: true on update...
This is the real reason I post to SO, its like always carrying an umbrella, its guaranteed not to rain.

Categories