I got error while validating field in mongodb, nodejs - node.js

These are the errors I got from backend while validating in model and received in 'err' variable. If I console.log(err), then it shows following errors.
Error [ValidationError]: employees validation failed: fullName: This field is required from model, email: This field is required from model
at ValidationError.inspect (D:\Programming\MERN\CRUD\node_modules\mongoose\lib\error\validation.js:61:24)
at formatValue (internal/util/inspect.js:703:31)
at inspect (internal/util/inspect.js:272:10)
at formatWithOptions (internal/util/inspect.js:1887:40)
at Object.Console.<computed> (internal/console/constructor.js:284:10)
at Object.log (internal/console/constructor.js:294:61)
at handleValidationError (D:\Programming\MERN\CRUD\routes\/employeeRoute.js:46:13)
at D:\Programming\MERN\CRUD\routes\/employeeRoute.js:33:17
at D:\Programming\MERN\CRUD\node_modules\mongoose\lib\model.js:4915:16
at D:\Programming\MERN\CRUD\node_modules\mongoose\lib\helpers\promiseOrCallback.js:16:11
at D:\Programming\MERN\CRUD\node_modules\mongoose\lib\model.js:4938:21
at D:\Programming\MERN\CRUD\node_modules\mongoose\lib\model.js:492:16
at D:\Programming\MERN\CRUD\node_modules\kareem\index.js:246:48
at next (D:\Programming\MERN\CRUD\node_modules\kareem\index.js:167:27)
at next (D:\Programming\MERN\CRUD\node_modules\kareem\index.js:169:9)
at Kareem.execPost (D:\Programming\MERN\CRUD\node_modules\kareem\index.js:217:3) {
errors: {
fullName: MongooseError [ValidatorError]: This field is required from model
at new ValidatorError (D:\Programming\MERN\CRUD\node_modules\mongoose\lib\error\validator.js:29:11)
at validate (D:\Programming\MERN\CRUD\node_modules\mongoose\lib\schematype.js:1178:13)
at D:\Programming\MERN\CRUD\node_modules\mongoose\lib\schematype.js:1161:7
at Array.forEach (<anonymous>)
at SchemaString.SchemaType.doValidate (D:\Programming\MERN\CRUD\node_modules\mongoose\lib\schematype.js:1106:14)
at D:\Programming\MERN\CRUD\node_modules\mongoose\lib\document.js:2378:18
at processTicksAndRejections (internal/process/task_queues.js:79:11) {
properties: [Object],
kind: 'required',
path: 'fullName',
value: '',
reason: undefined,
[Symbol(mongoose:validatorError)]: true
},
email: MongooseError [ValidatorError]: This field is required from model
at new ValidatorError (D:\Programming\MERN\CRUD\node_modules\mongoose\lib\error\validator.js:29:11)
at validate (D:\Programming\MERN\CRUD\node_modules\mongoose\lib\schematype.js:1178:13)
at D:\Programming\MERN\CRUD\node_modules\mongoose\lib\schematype.js:1161:7
at Array.forEach (<anonymous>)
at SchemaString.SchemaType.doValidate (D:\Programming\MERN\CRUD\node_modules\mongoose\lib\schematype.js:1106:14)
at D:\Programming\MERN\CRUD\node_modules\mongoose\lib\document.js:2378:18
at processTicksAndRejections (internal/process/task_queues.js:79:11) {
properties: [Object],
kind: 'required',
path: 'email',
value: '',
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: 'employees validation failed'
}
Now if I console.log('err.errors.fullName.message'). It works perfectly.
But if there are more keys, it's obvious that we need to use loop. So if I try to iterate through keys of object as follow, then it throws following error.
for(field in err.errors){
.......
.......
}
Error is:
ReferenceError: field is not defined
What's the problem here ?

First of all your backend should not give this type of error response as you mentioned in the above. This must be like a JSON response of errors. e.g
{ success: false, errors: [{fullName: "fullName is required"}] }
Coming to your question. If you want to show error properly you can loop through the error which you can pic by the err.errors
eg err.errors.forEach(error => console.log(error) )
But again this is a very wrong way to throw the validation error. To validate any data you can use joi, request-validator, validatorjs, etc. Which will give you a perfect error response as you want? Why I am giving stress on this because you are exposing entire directory, files, model name, etc.
I hope this may help you to solve your problem

Related

Trying to fetch spot price using uniswap SDK but transaction is throwing error LOK?

const quotedAmountOut = await quoterContract.callStatic.quoteExactInputSingle(
immutables.token0,
immutables.token1,
immutables.fee,
amountIn,
0
)
I created two erc20 dummy tokens and created a pool for them using uniswapV3Factory createPool() method and obtained the pool address. But when I wanted to fetch the spot price for the tokens i have used using the above script it is throwing following Error:
Error: call revert exception; VM Exception while processing transaction: reverted with reason string "LOK" [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ] (method="quoteExactInputSingle(address,address,uint24,uint256,uint160)", data="0x08c379a0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000034c4f4b0000000000000000000000000000000000000000000000000000000000", errorArgs=["LOK"], errorName="Error", errorSignature="Error(string)", reason="LOK", code=CALL_EXCEPTION, version=abi/5.7.0)
at Logger.makeError (/Users/apple/Desktop/solidity/deploy/node_modules/#ethersproject/contracts/lib/index.js:20:58)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
reason: 'LOK',
code: 'CALL_EXCEPTION',
method: 'quoteExactInputSingle(address,address,uint24,uint256,uint160)',
data: '0x08c379a0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000034c4f4b0000000000000000000000000000000000000000000000000000000000',
errorArgs: [ 'LOK' ],
errorName: 'Error',
errorSignature: 'Error(string)',
address: '0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6',
args: [
'<Token-1-Address>',
'<Token-2-Address>',
500,
BigNumber { _hex: '0x0de0b6b3a7640000', _isBigNumber: true },
0
],
transaction: {
data: '0xf7729d4300000000000000000000000008a2e53a8ddd2dd1d895c18928fc63778d97a55a0000000000000000000000006d7a02e23505a74143199abb5fb07e6ea20c6d6300000000000000000000000000000000000000000000000000000000000001f40000000000000000000000000000000000000000000000000de0b6b3a76400000000000000000000000000000000000000000000000000000000000000000000',
to: '0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6'
}
}
i found the issue here is your token address you provided, like token0 is WETH9 you must provide the exactly WETH9 token address, you can find it on etherscan.io

code: 'ENOENT', message: 'No such file or directory' when using opencv.js in node-project

I'm using opencv.js for face detection. When I run this html file with the linked js files (opecv.js,utils.js) using a live server, it works.But,now when I copy the same files in my node project,and render this html page, I get the following error.
Uncaught
ErrnoError {node: undefined, errno: 2, code: 'ENOENT', message: 'No such file or directory', setErrno: ƒ, …}
code: "ENOENT"
errno: 2
message: "No such file or directory"
node: undefined
setErrno: ƒ (errno)
arguments: null
caller: null
length: 1
name: ""
prototype: {constructor: ƒ}
[[FunctionLocation]]: opencv.js:24
[[Prototype]]: ƒ ()
[[Scopes]]: Scopes[4]
stack: "<generic error, no stack>"
[[Prototype]]: Error at Object.ensureErrnoError (http://127.0.0.1:3000/js/opencv.js:24:8492014) at Object.staticInit (http://127.0.0.1:3000/js/opencv.js:24:8492254) at http:

Trouble generating an Intent with delegateDirective from a TouchEvent handler (Alexa)

I need to confirm deleting a task from a button event. For this reason, I want Alexa to ask for confirmation, and therefore I need to generate a DeleteTaskIntent from my code.
I have tried this:
return handlerInput.responseBuilder.addDelegateDirective({
name: 'DeleteTaskIntent',
confirmationStatus: 'NONE',
slots: {
idTask:{
name: 'idTask',
value: idTask,
confirmationStatus: 'NONE'
}
}
}).getResponse();
In my TouchEventHandler, but after checking the request in the requestEnvelope, I see this:
request: {
type: 'System.ExceptionEncountered',
requestId: 'amzn1.echo-api.request.9c2cf5f4-2f2c-419c-898c-05bd5f096810',
timestamp: '2022-02-23T11:30:08Z',
locale: 'es-ES',
error: {
type: 'INVALID_RESPONSE',
message: 'Directive "Dialog.Delegate" cannot be used in response to an event'
},
cause: {
requestId: 'amzn1.echo-api.request.0494d80d-c6ac-41d6-b3a2-dffd97f427b5'
}
}
And the error
{
"name": "AskSdk.GenericRequestDispatcher Error"
}
also appears, which suggests that no handler can handle this case.
Any idea about what I'm doing wrong when trying to generate the Intent?

NotNullConstraintViolationException on npx mikro-orm migration:up

I modified my enitity and created it's migration using npx mikro-orm migration:create. Now when i try to apply the migration using npx mikro-orm migration:up.
I get the following error.
NotNullConstraintViolationException: alter table "user" add column "role" text check ("role" in ('admin', 'chief_editor', 'editor', 'user')) not null; - column "role" contains null values
at PostgreSqlExceptionConverter.convertException (C:\dev\nodejs\nestjs\blog-api\node_modules\#mikro-orm\postgresql\PostgreSqlExceptionConverter.js:24:24)
at PostgreSqlDriver.convertException (C:\dev\nodejs\nestjs\blog-api\node_modules\#mikro-orm\core\drivers\DatabaseDriver.js:194:54)
at C:\dev\nodejs\nestjs\blog-api\node_modules\#mikro-orm\core\drivers\DatabaseDriver.js:198:24
at processTicksAndRejections (node:internal/process/task_queues:93:5)
at Function.runSerial (C:\dev\nodejs\nestjs\blog-api\node_modules\#mikro-orm\core\utils\Utils.js:484:22)
at C:\dev\nodejs\nestjs\blog-api\node_modules\#mikro-orm\migrations\MigrationRunner.js:23:17
at PostgreSqlConnection.transactional (C:\dev\nodejs\nestjs\blog-api\node_modules\#mikro-orm\knex\AbstractSqlConnection.js:53:25)
at MigrationRunner.run (C:\dev\nodejs\nestjs\blog-api\node_modules\#mikro-orm\migrations\MigrationRunner.js:20:13)
previous error: alter table "user" add column "role" text check ("role" in ('admin', 'chief_editor', 'editor', 'user')) not null; - column "role" contains null values
at Parser.parseErrorMessage (C:\dev\nodejs\nestjs\blog-api\node_modules\pg-protocol\src\parser.ts:369:69)
at Parser.handlePacket (C:\dev\nodejs\nestjs\blog-api\node_modules\pg-protocol\src\parser.ts:188:21)
at Parser.parse (C:\dev\nodejs\nestjs\blog-api\node_modules\pg-protocol\src\parser.ts:103:30)
at TLSSocket.<anonymous> (C:\dev\nodejs\nestjs\blog-api\node_modules\pg-protocol\src\index.ts:7:48)
at TLSSocket.emit (node:events:376:20)
at TLSSocket.EventEmitter.emit (node:domain:470:12)
at addChunk (node:internal/streams/readable:311:12)
at readableAddChunk (node:internal/streams/readable:286:9)
at TLSSocket.Readable.push (node:internal/streams/readable:225:10)
at TLSWrap.onStreamRead (node:internal/stream_base_commons:192:23) {
length: 117,
severity: 'ERROR',
code: '23502',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: 'public',
table: 'user',
column: 'role',
dataType: undefined,
constraint: undefined,
file: 'tablecmds.c',
line: '4857',
routine: 'ATRewriteTable'
}
Why is a migration giving me this error?

Mongoose bulkWrite - Wrong type for 'q'

For my test suite, I want to bulkWrite test info in the database, and then bulk delete any of the test info entered throughout the test to come back to a clean slate. I do so by running a bulkWrite on the db to which I pass the content of a JSON file loaded via nodeJS's require statement.
The problem is that for the dataset
[ { deleteOne: { username: 'test-author' } } ]
passed to models[key].collection.bulkWrite(action[key]), where key is the name of the model of interest and action is the JSON file,I get the following error:
{ MongoError: Wrong type for 'q'. Expected a object, got a null.
at Function.MongoError.create (/var/www/website/server/node_modules/mongodb-core/lib/error.js:31:11)
at /var/www/website/server/node_modules/mongodb-core/lib/connection/pool.js:483:72
at authenticateStragglers (/var/www/website/server/node_modules/mongodb-core/lib/connection/pool.js:429:16)
at Connection.messageHandler (/var/www/website/server/node_modules/mongodb-core/lib/connection/pool.js:463:5)
at Socket.<anonymous> (/var/www/website/server/node_modules/mongodb-core/lib/connection/connection.js:339:20)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at Socket.Readable.push (_stream_readable.js:134:10)
at TCP.onread (net.js:548:20)
name: 'MongoError',
message: 'Wrong type for \'q\'. Expected a object, got a null.',
ok: 0,
errmsg: 'Wrong type for \'q\'. Expected a object, got a null.',
code: 14,
codeName: 'TypeMismatch' }
I have done some research and have been unable to find a solution to this problem. The error itself is pretty meaningless, so I can't grasp much out of it. Any idea how to solve the problem?
Any help would be greatly appreciated!
Cheers!
As per the MongoDB API, the deleteOne, deleteMany, updateOne, updateMany, replaceOne, and replaceMany operation requires to have a property filter which acts as the filter for the query.
However Mongoose's API shows the following (mistaken) example:
Character.bulkWrite([
...
{
deleteOne: {
{ name: 'Eddard Stark' }
}
}
]).then(handleResult);
Hence, the data sent over changes from:
[{
"deleteOne": { "username": "test-author" }
}]
to
[{
"deleteOne": { "filter": { "username": "test-author" }}
}]
I'll make sure to pass the message along to the mongoosejs dev group.

Resources