Express validator add a simple if-else structure - node.js

I have a field that can have 0 or any number. If it has 0 I want to do a validation, if it doesn't then I want to do other. How can I do that? This was my attempt.
app.post("/admin/updskill", [
body('i_sCatEdit')
.notEmpty().withMessage('The category id can not be empty.').bail()
.isNumeric({ no_symbols: true }).bail()
.trim().escape(),
body('sz_sCatEdit')
.if(body('i_sCatEdit').equals(0))
.isEmpty().withMessage('The category name must be empty.').bail().escape(),
body('sz_sCatEdit')
.if(body('i_sCatEdit').not().equals(0))
.notEmpty().withMessage('The category name can not be empty.').bail()
.exists({ checkNull: true, checkFalsy: true }).withMessage('The category name must exist (eg: not undefined, null).').bail()
.isLength({ min: 3, max: 149 }).withMessage('The category name min length is 3 characters and the max 149.').bail().escape()
In case the above code is not clear enough, this is pseudo code
if(i_sCatEdit === 0){
validation1
} else{
validation2
}

Related

Change the boolean value of 'available' Array (e.g at index 4 which taken from user input to false) using mongoose

Please see the image below:
enter image description here
use update like this
db.collection.update({},
{
$set: {
"available.3": false // index 3 means element number 4
}
})
if you are using mongoose your query is like this
Model.update({}, // model name instead of Model
{
$set: {
"available.3": false // index 3 means element number 4
}
})
https://mongoplayground.net/p/cMWOtIw5L_J

Is there a way to check if first Character is alphabet using express-validator?

case 'user_name': {
return [
check(
'content.data.userName',
'username need atleast one alphabet'
)
// .matches('(?=.[a-z])(?=.[0-9])')
.exists()
.trim()
.bail()
.isLength({ min: 6 })
.withMessage('User Name must be atleast have 6 characters')
.isLowercase()
.withMessage('Must be all small letters')
case 'user_name': {
return [
check(
'content.data.userName',
'username need atleast one alphabet'
)
// .matches('(?=.*[a-z])(?=.*[0-9])')
.exists()
.trim()
.bail()
.isLength({ min: 6 })
.withMessage('User Name must be atleast have 6 characters')
.isLowercase()
.withMessage('Must be all small letters')
This regular expression helps you to check the first character is alphabet or not.
^[a-zA-Z][\w\s-]+
First character can be only a-zA-Z
Not to allow special characters other than "space" and "hyphen(-)"
.matches(/^[a-zA-Z][\w\s-]+/)
Hope it works, Thank you!

NodeJS MongoDB Count entries with same value in field

I have the following collection
_id: someid
name: Name 1
status: 0
ref: 152
_id: someid
name: Name 1
status: 0
ref: 152
_id: someid
name: Name 1
status: 3
ref: 152
_id: someid
name: Name 1
status: 0
ref: 273
_id: someid
name: Name 1
status: 3
ref: 679
I'd like to get a result that tells me how many times "ref" appears with the same value where the entry has the status anything except 3. So for example the result I'm looking for is basically
{"152": 2, "273": 1, "679": 0}
Since "ref: 152" appears 2 times while the status is not 3 and "ref: 273" appears 1 times while the status is not 3. I'm using NodeJS, Express, and MongoDB. I've tried to aggregate which to an extent does work however since 679 has 0 the aggregation result omits "679: 0" and that causes the React template to throw an error declaring it undefined. Using aggregation also formats it differently so occasionally the wrong amount is displayed on different rows. I feel if I can access the count by using the reference number as the key it'd be accurate but I can't figure out how to achieve this.
EDIT: I have solved my issue like this:
const count = {}
docs.map((doc) => {
count[doc.ref] = 0
})
docs.map((doc) => {
doc.status < 3 && count[doc.ref]++
})
Which returns exactly what I specified I needed above however I was wondering if there was an even cleaner way to do it?
You can use Array.reduce() function as well.
const countRef = docs.reduce((count, doc) => {
count[doc.ref] = (doc.status !== 3) ? (count[doc.ref] || 0) + 1 : (count[doc.ref] || 0);
return count;
}, {});
// countRef - {"152": 2, "273": 1, "679": 0}

express-validator not wotking

i have create register form and i want to validate form. I am using express-validator middleware but i am able to validate. But if input type if valid value show still validation error message.
my module code is:
please help.
<pre>
const { body,sanitizeBody } = require('express-validator');
exports.registerform=[
body('fristName','Frist Name must be at least 2 chars long.').isLength({ min: 2 }),
body('lastName','Last name must be at least 2 chars long.').isLength({ min: 2 }),
body('email','must be a valid email.').isEmail(),
body('gender','please select gender.').isLength({ min: 2 }),
body('dob','Please provide date of birth.').isLength({ min: 2 }),
body('skills','Please any one skill.').isLength({ min: 2 }),
body('password','Password required').trim().notEmpty()
.isLength({ min: 5 }).withMessage('password must be minimum 5 length')
.matches(/(?=.*?[A-Z])/).withMessage('At least one Uppercase')
.matches(/(?=.*?[a-z])/).withMessage('At least one Lowercase')
.matches(/(?=.*?[0-9])/).withMessage('At least one Number')
.matches(/(?=.*?[#?!#$%^&*-])/).withMessage('At least one special character')
.not().matches(/^$|\s+/).withMessage('White space not allowed'),
body('confirm_password').custom((value, { req }) => {
if (value !== req.body.password) {
throw new Error('Password Confirmation does not match password');
}
})
]
</pre>
error messages
this is problem resolved. I validate validation middleware after multer middleware.
thank you.

Mongoose find all documents where array.length is greater than 0 & sort the data

I am using mongoose to perform CRUD operation on MongoDB. This is how my schema looks.
var EmployeeSchema = new Schema({
name: String,
description: {
type: String,
default: 'No description'
},
departments: []
});
Each employee can belong to multiple department. Departments array will look like [1,2,3]. In this case departments.length = 3. If the employee does not belong to any department, the departments.length will be equal to 0.
I need to find all employee where EmployeeSchema.departments.length > 0 & if query return more than 10 records, I need to get only employees having maximum no of departments.
Is it possible to use Mongoose.find() to get the desired result?
Presuming your model is called Employee:
Employee.find({ "departments.0": { "$exists": true } },function(err,docs) {
})
As $exists asks for the 0 index of an array which means it has something in it.
The same applies to a maximum number:
Employee.find({ "departments.9": { "$exists": true } },function(err,docs) {
})
So that needs to have at least 10 entries in the array to match.
Really though you should record the length of the array and update with $inc every time something is added. Then you can do:
Employee.find({ "departmentsLength": { "$gt": 0 } },function(err,docs) {
})
On the "departmentsLength" property you store. That property can be indexed, which makes it much more efficient.
By some reason, selected answer doesn't work as for now. There is the $size operator.
Usage:
collection.find({ field: { $size: 1 } });
Will look for arrays with length 1.
use can using $where like this:
await EmployeeSchema.find( {$where:'this.departments.length>0'} )
If anyone is looking for array length is greater than 1, you can do like below,
db.collection.find({ "arrayField.1" : { $exists: true }})
The above query will check if the array field has value at the first index, it means it has more than 1 items in the array. Note: Array index start from 0.

Resources