Dynamic key name (field name ) in joi validation [duplicate] - joi

This question already has an answer here:
Is there a way to validate dynamic key names in a Joi schema?
(1 answer)
Closed 5 years ago.
I need to validate dynamic key name in joi validation.
Following code is working but i need to change key name dynamic like 'phone'+this.props.date in following example
this.validatorTypes = {
'phone': Joi.string().min(10).max(10).required().label('Phone').options({
language: {
any: {
empty: 'is required'
},
string: {
min: 'length must be {{limit}} characters long'
}
}
}),
'name': Joi.string().min(3).max(30).required().label('Name').options({
language: {
any: {
empty: 'is required'
},
string: {
min: 'length must be {{limit}} characters long'
}
}
})
},
Thanks

['phone'+this.props.date]
worked for me
['phone'+this.props.date]: Joi.string().min(10).max(10).required().label('Phone').options({
language: {
any: {
empty: 'is required'
},
string: {
min: 'length must be {{limit}} characters long'
}
}
}),
['name'+this.props.date]: Joi.string().min(3).max(30).required().label('Name').options({
language: {
any: {
empty: 'is required'
},
string: {
min: 'length must be {{limit}} characters long'
}
}
})

Related

How to specify that at least one field is required out of three in total?

In my MongoDB model, there are 3 fields in total. Any document added to this collection must contain at least 1 of those 3 fields.
How can this be specified in the validation staged?
You can enum validation constraint which collection creation as below:
db.createCollection("jobs", {
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "status" ],
properties: {
status: {
enum: [ "Done", "Failed", "Initial" ],
description: "can only be one of the enum values and is required"
},
}
}
}
})
From the docs
Mongoose has several inbuilt validators. Strings have enum as one of the validators. So enum creates a validator and checks if the value is given in an array. E.g:
var userSchema = new mongooseSchema({
status: {
type: String,
enum : ['Done','Failed', 'Initial'],
default: 'Initial'
},
})
You can use custom validator to check if we have one of 3 keys in the object
const testSchema = mongoose.Schema({
field1: {
type: String,
validate: {
validator: function(v) {
if (this.field2 == undefined && this.field3 == undefined) {
return true;
}
return false;
},
},
},
field2: {
type: String,
validate: {
validator: function(v) {
if (this.field1 == undefined && this.field3 == undefined) {
return true;
}
return false;
},
},
},
field3: {
type: String,
validate: {
validator: function(v) {
if (this.field2 == undefined && this.field1 == undefined) {
return true;
}
return false;
},
},
},
});

mongoose : how to validate field depend on other field value

I want to require field depend on other field value; I have field paypaleEmail , I want it to be required when field role is "particular" otherwise not required.
paypalEmail: {
type: String,
required: function () { return this.role == 'particular', 'Paypal Email is required' },
trim: true,
validate: {
validator(email) {
return validator.isEmail(email)
},
message: '{VALUE} is not a valid email!',
},
lowercase: true,
},
when try to send request I got paypalEmail is required
The "required" function should return a boolean.
Your
function () { return this.role == 'particular', 'Paypal Email is required' }
Unconditionally returns string 'Paypal Email is required' which evaluates to true when casted to bool.
function () { return this.role == 'particular' }
Should do what you expect.

The method findOneAndUpdate change the id of my element in a array

I'm working with mongoDB, mongoose and graphQL. I'm trying to make an update in my DB.
I'm doing an update in an array called phones, the changes work perfectly, the only problem is that when the update ends, the value of the objectId changes.
// Models -> Schema Organization
const organizationSchema = new mongoose.Schema({
name: String,
address: String,
phones: [
{
number: Number,
prefix: Number
}
],
email: String
})
// Types -> Organization
type Response {
success: Boolean!
token: String
errors: [Error]
}
type Error {
path: String!
message: String!
}
input iOrganization {
_id: ID
arrID: ID
address: String
email: String
number: Int
prefix: Int
name: String
}
type Mutation {
updateOrgGeneric(iOrg: iOrganization): Response!
}
// Resolvers -> Organization (1st way)
Mutation: {
updateOrgGeneric: (parent, args, {models}) => {
return models.Organization.findOneAndUpdate(
{ "_id": args.iOrg._id, "phones._id": args.iOrg.arrID },
{ $set: { "phones.$": { number: args.iOrg.number, prefix: args.iOrg.prefix }} },
{new: true}
)
.then((resp) => {
console.log(resp);
return {
success: true,
errors: []
}
})
.catch((error) => {
return {
success: false,
errors: error
};
})
},
}
// Resolvers -> Organization (2nd way)
Mutation: {
updateOrgGeneric: (parent, args, {models}) => {
return models.Organization.findOneAndUpdate(
{ "_id": args.iOrg._id },
{ $set: { "phones.$[arr]": { number: args.iOrg.number, prefix: args.iOrg.prefix }} },
{new: true}
{ arrayFilters:[{ "arr._id": mongoose.Types.ObjectId(args.iOrg.arrID) }], new: true}
)
.then((resp) => {
console.log(resp);
return {
success: true,
errors: []
}
})
.catch((error) => {
return {
success: false,
errors: error
};
})
}
}
// Playground (http://localhost:5000/graphql)
mutation {
updateOrgGeneric(
iOrg: {
_id: "5bdbee1b794b972bc8562aeb"
arrID: "5bdcea7cae88be098c020b19"
number: 85239,
prefix: 862
}
){
success
errors {
path
message
}
}
}
Both _id, as arrID, exist in the BD.
In the playground example the initial arrID was: _id:ObjectId("5bdcea7cae88be098c020b19"), but after the update is another, example: _id:ObjectId("5bdcec0a2ab78533b4bd1d98"). What am I doing wrong?
Thank you!
Mongodb is a nosql database which means that every object in the database should consist of an Id and revision values. Once an update occurs the revision value changes as part of the update process to implement the changes made to the data object. Since your data object don't have the revision value then the id value changes. Because it is unique. Now I'm no expert with mongo but you should check the docs on how to persist data objects and change accordingly
In case anyone lands here (despite this being old post), the problem probably lies in trying to update the entire phones object, of which the overwritten _id is a part. Since there's a model defined for phonesin mongoose, it will try to create a new _id any time an entire new phones object is created.
Someone who wanted to keep the same id would need to $set only the fields they want to change, rather than the entire object. So
{ $set: { "phones.$[arr]": { number: args.iOrg.number, prefix: args.iOrg.prefix }} }
could be changed to
{ $set: { "phones.$[arr].number": args.iOrg.number, "phones.$[arr].prefix": args.iOrg.prefix } }

MongoDB Document Validation in Meteor?

How would one approach doing this (https://docs.mongodb.com/v3.2/core/document-validation/):
db.createCollection( "contacts",
{ validator: { $or:
[
{ phone: { $type: "string" } },
{ email: { $regex: /#mongodb\.com$/ } },
{ status: { $in: [ "Unknown", "Incomplete" ] } }
]
}
} )
In this:
// database.js
import { Mongo } from 'meteor/mongo';
export const Test = new Mongo.Collection('Test');
Thanks
you first need to define your schema in meteor.
Lists.schema = new SimpleSchema({
name: {type: String},
incompleteCount: {type: Number, defaultValue: 0},
userId: {type: String, regEx: SimpleSchema.RegEx.Id, optional: true}
});
This example defines a schema with a few simple rules:
We specify that the name field of a list is required and must be a
string.
We specify the incompleteCount is a number, which on insertion is
set to 0 if not otherwise specified.
We specify that the userId, which is optional, must be a string that
looks like the ID of a user document.
It’s pretty straightforward to validate a document with a schema. We can write:
const list = {
name: 'My list',
incompleteCount: 3
};
Lists.schema.validate(list);
In this case, as the list is valid according to the schema, the validate() line will run without problems. If however, we wrote:
const list = {
name: 'My list',
incompleteCount: 3,
madeUpField: 'this should not be here'
};
Lists.schema.validate(list);
Then the validate() call will throw a ValidationError which contains details about what is wrong with the list document.

mongodb : limit the possible values of a number field

I want to limit the choices for a field in mongo:
units : { type: Number, default: 1 },
But I would like to add this constraint: something like
authorized values: [1, 10, 100, 1000]
You are clearly using mongoose for which there is an enum type validator available:
var mySchema = new Schema({
"units": { "type": Number, "default": 1, "enum": [1,10,100,1000] }
})
There is no enum in MongoDB since there is no enum in json / bson, so yeah, you can't, you only can control entered values using your programming language (ex: fire an exception when an unexpected value is entered).
Mongoose's enum validator only works with string types, but you can use a custom validator to do this:
units : {
type: Number,
default: 1,
validate: {
validator: function (value) {
return [1, 10, 100, 1000].indexOf(value) !== -1;
},
message: 'Value must be one of 1, 10, 100, 1000'
}
}