CastError : try implement a route and right away get error - javascript

i do a project in nodejs with express and mongo
now i tried do implement a simple route but i get an error
//this is the route
router.patch('/resetPassword/:token', authController.resetPassword)
//this is the resetPassword function
exports.resetPassword = (req, res, next) => {
console.log("work")
}
But as soon as I click on the request I get the error even the consul.log is not read
C:\Users\5MATA\Desktop\first-real-project\BOOKS-PROJECT\BOOKS-BACK\node_modules\mongoose\lib\query.js:4498
const castError = new CastError();
^
CastError: Cast to ObjectId failed for value "resetPassword" (type string) at path "_id" for model "User"
at model.Query.exec (C:\Users\5MATA\Desktop\first-real-project\BOOKS-PROJECT\BOOKS-BACK\node_modules\mongoose\lib\query.js:4498:21)
at model.Query.Query.then (C:\Users\5MATA\Desktop\first-real-project\BOOKS-PROJECT\BOOKS-BACK\node_modules\mongoose\lib\query.js:4592:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
messageFormat: undefined,
stringValue: '"resetPassword"',
kind: 'ObjectId',
value: 'resetPassword',
path: '_id',
reason: Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
at new ObjectID (C:\Users\5MATA\Desktop\first-real-project\BOOKS-PROJECT\BOOKS-BACK\node_modules\bson\lib\bson\objectid.js:59:11)
at castObjectId (C:\Users\5MATA\Desktop\first-real-project\BOOKS-PROJECT\BOOKS-BACK\node_modules\mongoose\lib\cast\objectid.js:25:12)
at ObjectId.cast (C:\Users\5MATA\Desktop\first-real-project\BOOKS-PROJECT\BOOKS-BACK\node_modules\mongoose\lib\schema\objectid.js:246:12)
at ObjectId.SchemaType.applySetters (C:\Users\5MATA\Desktop\first-real-project\BOOKS-PROJECT\BOOKS-BACK\node_modules\mongoose\lib\schematype.js:1123:12)
at ObjectId.SchemaType._castForQuery (C:\Users\5MATA\Desktop\first-real-project\BOOKS-PROJECT\BOOKS-BACK\node_modules\mongoose\lib\schematype.js:1601:15)
at ObjectId.SchemaType.castForQuery (C:\Users\5MATA\Desktop\first-real-project\BOOKS-PROJECT\BOOKS-BACK\node_modules\mongoose\lib\schematype.js:1591:15)
at ObjectId.SchemaType.castForQueryWrapper (C:\Users\5MATA\Desktop\first-real-project\BOOKS-PROJECT\BOOKS-BACK\node_modules\mongoose\lib\schematype.js:1568:20)
at cast (C:\Users\5MATA\Desktop\first-real-project\BOOKS-PROJECT\BOOKS-BACK\node_modules\mongoose\lib\cast.js:332:32)
at model.Query.Query.cast (C:\Users\5MATA\Desktop\first-real-project\BOOKS-PROJECT\BOOKS-BACK\node_modules\mongoose\lib\query.js:4937:12)
at castQuery (C:\Users\5MATA\Desktop\first-real-project\BOOKS-PROJECT\BOOKS-BACK\node_modules\mongoose\lib\query.js:4738:18)
at model.Query.Query._findAndModify (C:\Users\5MATA\Desktop\first-real-project\BOOKS-PROJECT\BOOKS-BACK\node_modules\mongoose\lib\query.js:3598:23)
at model.Query.<anonymous> (C:\Users\5MATA\Desktop\first-real-project\BOOKS-PROJECT\BOOKS-BACK\node_modules\mongoose\lib\query.js:3164:8)
at model.Query._wrappedThunk [as _findOneAndUpdate] (C:\Users\5MATA\Desktop\first-real-project\BOOKS-PROJECT\BOOKS-BACK\node_modules\mongoose\lib\helpers\query\wrapThunk.js:16:8)
at C:\Users\5MATA\Desktop\first-real-project\BOOKS-PROJECT\BOOKS-BACK\node_modules\kareem\index.js:370:33
at processTicksAndRejections (node:internal/process/task_queues:78:11),
valueType: 'string'
}

This is how you do it.
route.js
const router = require("express").Router();
const adminCtrl = require("./adminCtrl");
router.post("/login", adminCtrl.adminLogin);
adminCtrl.js
exports.adminLogin = (req, res,next) => {
}

Related

CastError: in mongoose

app.post("/delete", function (req, res) {
const checkedId = (req.body.checkBox);
console.log(checkedId);
Item.findByIdAndRemove(checkedId, function (err) {
if (!err) {
console.log("Successfully deleted");
redirect("/");
}
})
})
I don't know what is wrong with this code but I am getting this error,
CastError: Cast to ObjectId failed for value "63aae09d2679f102298b87b0 " (type string) at path "_id" for model "Item"
at model.Query.exec (D:\WebDevelopment\EJS\node_modules\mongoose\lib\query.js:4913:21)
at Query.findOne (D:\WebDevelopment\EJS\node_modules\mongoose\lib\query.js:2616:8)
at Function.findOne (D:\WebDevelopment\EJS\node_modules\mongoose\lib\model.js:2363:13)
at Function.findById (D:\WebDevelopment\EJS\node_modules\mongoose\lib\model.js:2309:15)
at D:\WebDevelopment\EJS\app.js:62:10
at Layer.handle [as handle_request] (D:\WebDevelopment\EJS\node_modules\express\lib\router\layer.js:95:5)
at next (D:\WebDevelopment\EJS\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (D:\WebDevelopment\EJS\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (D:\WebDevelopment\EJS\node_modules\express\lib\router\layer.js:95:5)
at D:\WebDevelopment\EJS\node_modules\express\lib\router\index.js:284:15 {
messageFormat: undefined,
stringValue: '"63aae09d2679f102298b87b0 "',
kind: 'ObjectId',
value: '63aae09d2679f102298b87b0 ',
path: '_id',
reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer
at new BSONTypeError (D:\WebDevelopment\EJS\node_modules\bson\lib\error.js:41:28)
at new ObjectId (D:\WebDevelopment\EJS\node_modules\bson\lib\objectid.js:67:23)
What should I do I want to delete the row having that particular _id, please help I am stuck to this problem and not getting any solution
Seams that your entry has an extra space in the end: 63aae09d2679f102298b87b0 .
Try to trim the entry before sending it to the function.

Including subschemas in schemas doesn't seem to work for mongoose

This is how I defined my subschema and schema
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const JobSchema = new Schema ({
jobname: String,
jobstatus: String
})
const DataSchema = new Schema ({
username: {
type: String,
required: true,
unique: true
},
jobs: [JobSchema]
});
module.exports = mongoose.model("data", DataSchema);
This block of code is to utilize the schema above as a model
const express = require("express");
const router = express.Router();
const Data = require("../../models/Data");
router.post("/", (req, res) => {
const newData = new Data({
username: req.body.username,
jobs: req.body.jobs
});
newData
.save()
.then(data => res.json(data))
.catch(err => console.log(err));
});
module.exports = router;
Data I attempted to put in:
{
username: France,
jobs: [{jobname: Google, jobstatus: applied}]
}
Error:
Error: data validation failed: jobs: Cast to embedded failed for value "'[{jobname: Google, jobstatus: applied}]'" at path "jobs"
at ValidationError.inspect (/Users/Desktop/server/node_modules/mongoose/lib/error/validation.js:48:26)
at formatValue (internal/util/inspect.js:723:31)
at inspect (internal/util/inspect.js:289:10)
at formatWithOptionsInternal (internal/util/inspect.js:1918:40)
at formatWithOptions (internal/util/inspect.js:1802:10)
at Object.Console.<computed> (internal/console/constructor.js:304:10)
at Object.log (internal/console/constructor.js:314:61)
at /Users/Desktop/server/routes/api/data.js:14:31
at processTicksAndRejections (internal/process/task_queues.js:97:5) {
errors: {
jobs: CastError: Cast to embedded failed for value "'[{jobname: Google, jobstatus: applied}]'" at path "jobs"
at DocumentArrayPath.cast (/Users/Desktop/server/node_modules/mongoose/lib/schema/documentarray.js:449:19)
at DocumentArrayPath.cast (/Users/Desktop/server/node_modules/mongoose/lib/schema/documentarray.js:378:17)
at DocumentArrayPath.SchemaType.applySetters (/Users/Desktop/server/node_modules/mongoose/lib/schematype.js:1031:12)
at model.$set (/Users/Desktop/server/node_modules/mongoose/lib/document.js:1203:20)
at model._handleIndex (/Users/Desktop/server/node_modules/mongoose/lib/document.js:979:14)
at model.$set (/Users/Desktop/server/node_modules/mongoose/lib/document.js:920:22)
at model.Document (/Users/Desktop/server/node_modules/mongoose/lib/document.js:137:12)
at model.Model (/Users/Desktop/server/node_modules/mongoose/lib/model.js:106:12)
at new model (/Users/Desktop/server/node_modules/mongoose/lib/model.js:4695:15)
at /Users/Desktop/server/routes/api/data.js:7:21
at Layer.handle [as handle_request] (/Users/Desktop/server/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/Desktop/server/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/Desktop/server/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/Desktop/server/node_modules/express/lib/router/layer.js:95:5)
at /Users/Desktop/server/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/Desktop/server/node_modules/express/lib/router/index.js:335:12) {
stringValue: `"'[{jobname: Google, jobstatus: applied}]'"`,
messageFormat: undefined,
kind: 'embedded',
value: "'[{jobname: Google, jobstatus: applied}]'",
path: 'jobs',
reason: ObjectParameterError: Parameter "obj" to Document() must be an object, got [{jobname: Google, jobstatus: applied}]
at EmbeddedDocument.Document (/Users/Desktop/server/node_modules/mongoose/lib/document.js:90:11)
at EmbeddedDocument [as constructor] (/Users/Desktop/server/node_modules/mongoose/lib/types/embedded.js:42:12)
at new EmbeddedDocument (/Users/Desktop/server/node_modules/mongoose/lib/schema/documentarray.js:115:17)
at DocumentArrayPath.cast (/Users/Desktop/server/node_modules/mongoose/lib/schema/documentarray.js:442:22)
at DocumentArrayPath.cast (/Users/Desktop/server/node_modules/mongoose/lib/schema/documentarray.js:378:17)
at DocumentArrayPath.SchemaType.applySetters (/Users/Desktop/server/node_modules/mongoose/lib/schematype.js:1031:12)
at model.$set (/Users/Desktop/server/node_modules/mongoose/lib/document.js:1203:20)
at model._handleIndex (/Users/Desktop/server/node_modules/mongoose/lib/document.js:979:14)
at model.$set (/Users/Desktop/server/node_modules/mongoose/lib/document.js:920:22)
at model.Document (/Users/Desktop/server/node_modules/mongoose/lib/document.js:137:12)
at model.Model (/Users/Desktop/server/node_modules/mongoose/lib/model.js:106:12)
at new model (/Users/Desktop/server/node_modules/mongoose/lib/model.js:4695:15)
at /Users/Desktop/server/routes/api/data.js:7:21
at Layer.handle [as handle_request] (/Users/Desktop/server/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/Desktop/server/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/Desktop/server/node_modules/express/lib/router/route.js:112:3)
}
},
_message: 'data validation failed'
}
I have read from several sources on the internet that the idea of subschemas(a.k.a subdocuments) is possible. However, when I try to implement it as shown above, it fails to work. What is the reason behind this?
The error looks like you are assigning a string to jobs instead of the array object. I think what you are currently saving is
{
username: "France",
jobs: "[{jobname: Google, jobstatus: applied}]" // the whole array as string
}
What you should be saving is
{
username: "France",
jobs: [{jobname: "Google", jobstatus: "applied"}]
}
Please console log the req.body.jobs and check if its a proper JSON array
You can't use schema in another schema by storing it in a "jobs".
You can give a reference to "jobschema" as below.
jobs : [{
type: Schema.ObjectId,
ref: 'JobSchema'
}]

Getting error while POST request with JSON

This is my server.js file code . I am trying to push the JSON content in the user object , but i am getting following error. Please tell me where i am going wrong.
const express = require('express')
const app = express()
const bcrypt = require('bcrypt')
const bodyParser = require('body-parser')
app.use(express.json())
const users = []
app.get('/users', (req, res) => {
JSON.stringify(users)
res.json(users)
})
app.post('/users', (req, res) => {
const user = {
name: req.body.name,
password: req.body.password
}
users.push(user)
res.status(201).send()
})
app.listen(3000, console.log("server started"));
I used an extension in VS code called REST client.
GET http: //localhost:3000/users
#####
POST http: //localhost:3000/users
Content-Type: application/json
{
"name": "Tanay",
"password": "password"
}
When I'm firing POST request it shows the error - SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at parse (C:\Users\TANAY RAJ\Desktop\nodePassport\Wsimplified\node_modules\body-parser\lib\types\json.js:89:19)
at C:\Users\TANAY RAJ\Desktop\nodePassport\Wsimplified\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (C:\Users\TANAY RAJ\Desktop\nodePassport\Wsimplified\node_modules\raw-body\index.js:224:16)
at done (C:\Users\TANAY RAJ\Desktop\nodePassport\Wsimplified\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (C:\Users\TANAY RAJ\Desktop\nodePassport\Wsimplified\node_modules\raw-body\index.js:273:7)
at IncomingMessage.emit (events.js:322:22)
at endReadableNT (_stream_readable.js:1187:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
Can be something wrong with the user variable. Can you check this:
const user={'name':req.body.name,'password':req.body.password}
Update
I tried out:
var data = [];
const user={'name':"Deshan",'password':"password"}
data.push(user);
console.log(data);
And the result was as follow:
[ { name: 'Deshan', password: 'password' } ]
So it maybe a problem with the request data.

How to fix unhandled promise rejection warning, cast to objectid failed

I'm new to mongoose, I am trying to set up a get route to '/featured' in my api but am getting the following error '(node:8989) UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "featured" at path "_id" for model "Blog"'
I am fairly sure I'm just doing something wrong when setting up my router for my blogs. I've tried using .find({'featured': true}), tried .find({featured: true}), tried .find().where('featured', true), tried .find().where('featured').equals(true) and all of them result in the same UnhandledPromiseRejectionWarning: CastError
here is my blog schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BlogSchema = new Schema({
title: { type: String, required: true },
article: { type: String, required: true },
published: { type: Date, required: true },
featured: { type: Boolean, required: true },
author: { type: Schema.Types.ObjectId, ref: 'User', required:true}
});
module.exports = mongoose.model('Blog', BlogSchema);
here is the route I am having trouble with in blogs.js
router.get('/featured', (req, res) =>
{
Blog
.find({'featured': true})
.then(blogs =>
{
if(blogs){
res.status(200).json(blogs)
}
else console.log('blogs not found');
})
.catch(err => console.log(err));
});
here is the error stack trace
(node:16486) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
Server is listening on http://localhost:8080
(node:16486) UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "featured" at path "_id" for model "Blog"
at new CastError (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/mongoose/lib/error/cast.js:29:11)
at ObjectId.cast (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/mongoose/lib/schema/objectid.js:244:11)
at ObjectId.SchemaType.applySetters (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/mongoose/lib/schematype.js:948:12)
at ObjectId.SchemaType._castForQuery (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/mongoose/lib/schematype.js:1362:15)
at ObjectId.SchemaType.castForQuery (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/mongoose/lib/schematype.js:1352:15)
at ObjectId.SchemaType.castForQueryWrapper (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/mongoose/lib/schematype.js:1331:15)
at cast (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/mongoose/lib/cast.js:307:32)
at model.Query.Query.cast (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/mongoose/lib/query.js:4575:12)
at model.Query.Query._castConditions (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/mongoose/lib/query.js:1783:10)
at model.Query.<anonymous> (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/mongoose/lib/query.js:2038:8)
at model.Query._wrappedThunk [as _findOne] (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/mongoose/lib/helpers/query/wrapThunk.js:16:8)
at process.nextTick (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/kareem/index.js:369:33)
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
(node:16486) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
I expect to have the "/featured" route return all blogs where the "featured" boolean value is true, but instead I am getting this error no matter what permutations of the query I try for this route
I'm new to mongoose, I am trying to set up a get route to '/featured' in my api but am getting the following error '(node:8989) UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "featured" at path "_id" for model "Blog"'
This is saying that you have a document in your mongo collection that looks like {_id: "featured"}. "featured" isn't an ObjectId, so mongoose is erroring when it sees that document because it doesn't know how to handle it.

Node/Mongoose Error: ValidationError

This is my server.js. When I run node server.js then use PostMan to post json, it gives me the following error.
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
app.use(bodyParser.json())
app.get('/api/posts', function(req, res) {
res.json([
{
username: '#rodandrew95',
body: 'node rocks!'
}
])
})
app.listen(3000, function() {
console.log('Server listening on', 3000)
})
var Post = require('./models/post')
app.post('/api/posts', function(req, res, next) {
// console.log('post received')
// console.log(req.body.username)
// console.log(req.body.body)
// res.sendStatus(201)
var post = new Post({
username: req.body.username,
body: req.body.body
});
post.save(function (err, post) {
if (err) { return next(err) }
res.sendStatus(201).json(post)
})
})
The error:
(node:6863) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
ValidationError: Post validation failed
at MongooseError.ValidationError (/Users/andrewrodrigues/Desktop/write_modern/ch_1/node_modules/mongoose/lib/error/validation.js:23:11)
at model.Document.invalidate (/Users/andrewrodrigues/Desktop/write_modern/ch_1/node_modules/mongoose/lib/document.js:1486:32)
at /Users/andrewrodrigues/Desktop/write_modern/ch_1/node_modules/mongoose/lib/document.js:1362:17
at validate (/Users/andrewrodrigues/Desktop/write_modern/ch_1/node_modules/mongoose/lib/schematype.js:705:7)
at /Users/andrewrodrigues/Desktop/write_modern/ch_1/node_modules/mongoose/lib/schematype.js:742:9
at Array.forEach (native)
at SchemaString.SchemaType.doValidate (/Users/andrewrodrigues/Desktop/write_modern/ch_1/node_modules/mongoose/lib/schematype.js:710:19)
at /Users/andrewrodrigues/Desktop/write_modern/ch_1/node_modules/mongoose/lib/document.js:1360:9
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
I'm trying to learn the MEAN stack through "Write Modern Web Apps with the MEAN Stack" but I'm running into issues all the time, even when I follow the code and instructions exactly. Can anyone help understand this error, and possibly recommend some good resources for learning the mean stack?
This error is triggered because you have provided a mongoose validation in
your schema (in /models/post) and that validation is failing.
For instance, if you provided your model like this :
var postSchema = new Schema({
"username": String,
"body": String,
"email": {
type: String,
required: true
}
});
var Post = mongoose.model('Post', postSchema);
This would fail because email required validator is not respected. Find a full list of validators here.
Side note : res.sendStatus(201).json(post) will set the json body and content-type header after sending a response with 201 status. To send both use :
res.status(201).json(post)

Categories

Resources