Changing default Boolean value for Joi is not working properly - javascript

I'm using joi Sandbox v17.7.0 at https://joi.dev/tester/
Schema:
Joi.object({
id: Joi.when(Joi.ref('query.byRef'), {
is: Joi.boolean().valid(true),
then: Joi.string().min(1),
otherwise: Joi.number().positive(),
}),
query: Joi.object(
{
byRef: Joi.boolean().default(false)
}
),
})
And my data is
{
id: "1",
}
Basically, I want id to be parsed as integer when byRef = false, and as string when byRef = true. When I pass by ref value in my data, as
{
id: "1",
query: {
byRef: false,
}
}
Then it works as expected. But when I omit it, the default value doesn't work as expected. Whether I change it to true or false.
I've tried it as
is: true
that also doesn't work. What can I do to make sure default value is set?

Related

Vue cannot get value of object in data options

So I have a data options like this
data() {
return {
userPayload: {
description: '',
languageCodes: [],
facebookUrl: '',
youtubeUrl: ''
},
}
},
Later I applied some functions to fill out each attributes in data. Then when I want to submit the data using handleSaveData(), I passed this userPayload object to axios and turns out it's only read the value of description attributes.
handleSaveData() {
...
const userPayload = {
description: this.userPayload.description,
profile: {
languageCodes: this.userPayload.languageCodes,
facebookUrl: this.userPayload.facebookUrl,
youtubeUrl: this.userPayload.youtubeUrl
}
}
console.log(this.userPayload)
// this one contains value of all attributes
console.log(userPayload)
// this one only shows value of description attributes, while the others are empty string or empty array
// i expect it also return value of another attributes
// because i already access it with this.userPayload.{attributeName}
}
I already tried out deepClone userPayload object but it doesn't work

Mongoose update nested object in array of record

I am currently having a problem where I am trying to update an of a nested array in a Mongoose record.My schema is as follows:
const customerSchema = new mongoose.Schema({
kimCustomerId: {
type: Number,
required: true
},
addresses: [
{
created: Date,
updated: Date,
addressInfo: {
type: { type: String },
typeOfAddress: String,
careOf: String,
address: String,
addressRow1: String,
addressRow2: String,
zipcode: String,
city: String,
countryCode: String,
physicalAddressType: String,
validFrom: Date,
validTo: Date
}
}
],
.....
As you can see, the adrress array for each record holds many addresses. I want to be able to pass through an update object and update the properties inside the addressInfo nested object inside a particular array object. Here is my query as it stands:
const updated = await db.models.customers.findOneAndUpdate(
{
_id: customer._id,
'addresses.addressId': addressData.addressId
},
{ $set: { 'addresses.$': addressData } },
{ new: true }
);
and an example of an object I pass through to update a record:
{
addressId: officialAddressExists.addressId,
addressInfo: {
validTo: new Date().toISOString()
}
}
What I want to happen is, when I pass this object to the schema method, I want to select the correct address by the values 'kimCustomerId' and 'addressId' (which I have working fine) then only update the values of the 'addressInfo' nested object that I have passed and keep the ones not passed as they are, in this case the 'validTo' field but it can be any number of them updated. It is overwriting the whole 'addressInfo' nestedObject at the moment so I presume I have to do some kind of set operation on that nested object as well but I am unsure how.
Is anyone able to point me in the right direction here?
Thanks!
There is no straight way to do this in query, you can do it in your client side, something like,
// Sample body request
let addressData = {
addressId: 1,
addressInfo: {
validTo: new Date().toISOString(),
typeOfAddress: "Home",
address: "ABC"
}
};
let set = {};
for (let key in addressData.addressInfo) {
set["addresses.$.addressInfo." + key] = addressData.addressInfo[key];
}
console.log(set);
Pass set variable in to your query,
const updated = await db.models.customers.findOneAndUpdate(
{
_id: customer._id,
'addresses.addressId': addressData.addressId
},
{ $set: set },
{ new: true }
);

nodejs objects property can only be changed to int and not string

i just got this wierd issue in which the code below returns the refno for all Object in the array as expected But
let records = await Expense.find({}).exec(); // records is an array of objects [{},{}]
for (let obj of records) { // the obj has a refno property which i want to change
obj.refno = 0 // this works as expected by changing refno property to 0
}
console.log(records)
this code of code below of chaning the properties value to string Does not work
for (let obj of records) {
obj.refno = "QM"+obj.refno
}
console.log(records) // IN this the refno. doesnt change
my requirment is to change the refno to a string
//the object
{
_id: 5efed2c813b03d331e4dc052,
refno: 102,
project: 'EV Battery Pack',
invoiceno: 'dia',
description: 'black frame',
date: '2020-07-03',
}
so chaning the property to other number works but not to string , i cant get how this happens or am i missing something ?, anyways i got around this by declaring another property and storing the string in it but I dont know why the int cant be changed to string inside object
can some one explain why this happens
thanks for help
Edit : schema of expense
var schema = new Schema({
refno: { type: Number, require: true },
project: { type: String, require: true },
projectid: { type: Number, require: true },
invoiceno: { type: String, require: true },
description: { type: String, require: true },
date: { type: String, require: true },
INR: { type: Number, require: true },
USD: { type: Number, require: true },
remarks: { type: String, require: true },
});
The result of your .find().exec() call are mongoose documents which do not allow to modify their values if the resulting datatype is not compliant with the schema-constraints.
However, you can use .lean() (see https://mongoosejs.com/docs/api.html#query_Query-lean) on the mongoose document which will convert it to a plain js-object which you then can modify arbitrarily:
let records = await Expense.find({}).exec().lean();

Yup conditional object validation not working

I'm trying to define a Yup validation for an object - if a defined sibling is set to true, the field of type object should be required, otherwise not
Example:
const { object, string, number, date, boolean } = require('yup')
const contactSchema = object({
isBig: boolean(),
count: number()
.when('isBig', {
is: true, // alternatively: (val) => val == true
then: number().min(5),
otherwise: number().min(0),
}),
complexOne: object({
simpleOne: string(),
})
.when('isBig', {
is: true,
then: object().required(),
otherwise: object(),
})
})
The object passed into the validation:
{
isBig: true,
count: -1,
}
As you can see, I intentionally don't pass the complexOne since I want Yup to display the error. The validation for the count works correctly - if the value is less than 0 and the isBig is set to true, Yup will correctly display an error message ValidationError: count must be greater than or equal to 5
Unfortunately, it completely ignores the conditional validation set for the complexOne field. Either yup does not support the when for object types or I'm doing something incorrectly.
Thanks for any help
you must set strict option to true in order to only validate the object, and skip any coercion or transformation:
contactSchema.validate(contact, { strict: true })
.then(obj => {
console.log(obj)
}, err => {
console.log(err.message)
})
Demo:

Changing mongoose model causes code to error

In my user schema I have a property:
verification: {
phoneVerification: {
verified: Boolean,
code: String,
},
however, if I change it to this:
verification: {
phoneVerification: {
verified: Boolean,
code: String,
carrier: String,
type: String
},
It changes my Javascript output which ends up causing an error for me.
let user = await User.findOne({ _id: req.user._id }, '-salt -password').exec();
user.verification.phoneVerification = {};
console.log(user.verification);
This code at first outputs:
{ phoneVerification: null,
mailVerification: { verified: false, code: '1c7d55d3d2e64ae98e82' } }
Then ends up outputting:
{ mailVerification: { verified: false, code: '1c7d55d3d2e64ae98e82' } }
After my model has been changed.
Because of the fact that phoneVerification isn't instantiated, my code is giving me back an error.
It's very weird, what is causing this to happen?
Edit:
I'm asking why adding another subproperty to the property on the user model, I can no longer instantiate this verification.phoneVerification object to eventually save properties to it. It's not a duplicate of above question.

Categories

Resources