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.
Related
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) => {
}
This is the code from server side i have created but says :
[
'60c65094d9e1242a18cf84da',
'60c650d7d9e1242a18cf84db',
'60c650fbd9e1242a18cf84dc'
]
Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
at new ObjectID (F:\Web Development\Assignments\fresh-mart-server\node_modules\bson\lib\bson\objectid.js:59:11)
at ObjectID (F:\Web Development\Assignments\fresh-mart-server\node_modules\bson\lib\bson\objectid.js:40:43)
at F:\Web Development\Assignments\fresh-mart-server\index.js:49:36
at Layer.handle [as handle_request] (F:\Web Development\Assignments\fresh-mart-server\node_modules\express\lib\router\layer.js:95:5)
at next (F:\Web Development\Assignments\fresh-mart-server\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (F:\Web Development\Assignments\fresh-mart-server\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (F:\Web Development\Assignments\fresh-mart-server\node_modules\express\lib\router\layer.js:95:5)
at F:\Web Development\Assignments\fresh-mart-server\node_modules\express\lib\router\index.js:281:22
at Function.process_params (F:\Web Development\Assignments\fresh-mart-server\node_modules\express\lib\router\index.js:335:12)
at next (F:\Web Development\Assignments\fresh-mart-server\node_modules\express\lib\router\index.js:275:10)
app.post('/productsByKeys',(req,res)=> {
console.log("found:ids",req.body)
const productKeys = req.body;
productCollection.find({_id: {$in :ObjectID(productKeys)}})
.toArray((err,items)=> {
res.send(items);
console.log(" found by ids: ",documents)
console.log("RESPONSE :",err)
})
})
Instead of converting you array into ObjectId(), convert individual items inside the array into ObjectIds.
const productKeys = req.body;
let convertedKeys = productKeys.map((x) => ObjectID(x));
productCollection.find({_id: {$in :convertedKeys}})
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'
}]
i get the following error, using the jwt-simple lib:
TypeError: Cannot read property 'split' of undefined
at module.exports (C:\my_application\services\mylist.js:5:40)
at Layer.handle [as handle_request] (C:\my_application\node_modules\express\lib\router\layer.js:95:5)
at next (C:\my_application\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch (C:\my_application\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\my_application\node_modules\express\lib\router\layer.js:95:5)
at C:\my_application\node_modules\express\lib\router\index.js:277:22
at Function.process_params (C:\my_application\node_modules\express\lib\router\index.js:330:12)
at next (C:\my_application\node_modules\express\lib\router\index.js:271:10)
at C:\my_application\api.js:39:3
at Layer.handle [as handle_request] (C:\my_application\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\my_application\node_modules\express\lib\router\index.js:312:13)
at C:\my_application\node_modules\express\lib\router\index.js:280:7
at Function.process_params (C:\my_application\node_modules\express\lib\router\index.js:330:12)
at next (C:\my_application\node_modules\express\lib\router\index.js:271:10)
at logger (C:\my_application\node_modules\morgan\index.js:144:5)
at Layer.handle [as handle_request] (C:\my_application\node_modules\express\lib\router\layer.js:95:5)
and here is mylist.js file:
var jwt = require('jwt-simple');
module.exports = function (req, res) {
var token = req.headers.authorization.split(' ')[1];
var payload = jwt.decode(token, "shhh..");
if(!payload.sub) {
res.status(401).send({
message: 'Authentication failed'
});
}
if(!req.headers.authorization){
return res.status(401).send({
message: 'You are not authorized'
});
}
res.json(mylist);
};
var mylist = [
'Proj 1',
'Proj 2',
'Proj 3',
'Proj 4'
];
i am trying to see if the user is authorized to access the mylist resource on frontend.
does anyone have any idea?
you assume it's a string, even if you don't know if there really is a string there.
You should add some error checking first
module.exports = function (req, res) {
if (typeof req.headers.authorization !== 'string') {
res.sendStatus(400);
return;
}
var tokens = req.headers.authorization.split(' ');
if (tokens.length < 2) {
res.sendStatus(400);
return;
}
var token = tokens[1];
var payload = jwt.decode(token, "shhh..");
if(!payload.sub) {
res.status(401).send({
message: 'Authentication failed'
});
}
...
};
Edit: But why exactly do you want the second token and not the first?
Heres my code relative to the problem:
server.js file:
app.post('/user', function(req,res){
console.log(req.body);
var user = mongoose.Schema('User',req.body);
user.save(function(err,user){
if(err) console.log(err);
console.log("Successfully added user to MongoDB");
});
res.sendStatus(200);
});
Angular Controller:
app.controller('RegisterController',['$scope','$http',function($scope,$http){
$scope.submitData = function(user){
var dob = user.dob.day.toString()+"/"+user.dob.month.toString()+"/"+user.dob.year.toString();
user.dob = dob;
var post = $http.post('/user', user);
post.success(function(data,status,headers,config){
console.log(data);
console.log(status);
console.log('Success!');
});
}
$scope.countTo= function(count){
var array = [];
for(i = 1; i<=count; i++){
array.push(i);
}
return array;
}
$scope.countFrom = function(startingPoint,count){
var numbers = [];
for(i=startingPoint; i>startingPoint-count;i--){
numbers.push(i);
}
return numbers;
}
}
Mongoose Schema:
var mongoose = require('mongoose');
var userSchema = mongoose.Schema({
email: {
type:String,
required: true
},
dob: {
type: String,
required: true
},
password: {
type:String,
required:true
},
postcode: {
type:String,
required:true
},
address: {
type:String,
required:true
}
});
var User = mongoose.model('User',userSchema);
This is the error:
SyntaxError: Unexpected token o
at Object.parse (native)
at P:\learning\Blink\server.js:35:41
at Layer.handle [as handle_request] (P:\learning\Blink\node_modules\express\lib\router\layer.js:95:5)
at next (P:\learning\Blink\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch (P:\learning\Blink\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (P:\learning\Blink\node_modules\express\lib\router\layer.js:95:5)
at P:\learning\Blink\node_modules\express\lib\router\index.js:277:22
at Function.process_params (P:\learning\Blink\node_modules\express\lib\router\index.js:330:12)
at next (P:\learning\Blink\node_modules\express\lib\router\index.js:271:10)
at serveStatic (P:\learning\Blink\node_modules\express\node_modules\serve-static\index.js:74:16)
at Layer.handle [as handle_request] (P:\learning\Blink\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (P:\learning\Blink\node_modules\express\lib\router\index.js:312:13)
at P:\learning\Blink\node_modules\express\lib\router\index.js:280:7
at Function.process_params (P:\learning\Blink\node_modules\express\lib\router\index.js:330:12)
at next (P:\learning\Blink\node_modules\express\lib\router\index.js:271:10)
at P:\learning\Blink\node_modules\body-parser\lib\read.js:129:5
The error occurs when I click the send button on the website... Any help please?
It looks like you are doing the Mongoose side of things a little wrong here. Not 100% sure this is the cause of your error, but it's still problematic.
var user = mongoose.Schema('User',req.body);
This isn't doing what you think it does. Schema expects an object representing the Schema as the first argument e.g., {email:String, dob:String}. Passing the string 'User' here would not work.
Instead, you want to reference the model you've already defined. You can do so by either
exporting and subsequently including your user model as a module like var User = require('UserModel.js')
or directly referencing the model from Mongoose (assuming it's defined in the app before you call it) like var User = mongoose.model('User);
Once you have a reference to the Model object you can initialize a new document. In your case you probably want your code to read something like
var user = new User(req.body);
user.save(function(err,user){...}
Try that and then let us know if you are still seeing that error.