Select document by _id accessing database from MongoDB MLAB in Node.js - node.js

I am trying to access the document from MongoDB which was hosted on MLab but getting following error while access document with _id. Following is code for your reference
var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
var db = mongojs('mongodb://<<UserName>>:<<Password>>#aadds157248.mlab.com:57248/<<DatabaseName>>',['temp1']);
router.get('/todo/:id',function(req,res,next){
var ObjectID = mongojs.ObjectID;
var o_id = new ObjectID (req.params.id);
db.temp1.findOne({
'_id': o_id
},
function(err,temp1){
if (err){
res.send(err);
}
else {
res.json(temp1);
}
})
});
But getting below error when try to access the URL : http://localhost:3000/api/v1/todo/5870f7f1f36d2872530d26f1
TypeError: hex is not a function
at Function.from (native)
at Function.from (native)
at new ObjectID (C:\Kamlesh\Angular2\meantodos\node_modules\bson\lib\bson\objectid.js:52:32)
at C:\Kamlesh\Angular2\meantodos\routes\todos.js:23:14
at Layer.handle [as handle_request] (C:\Kamlesh\Angular2\meantodos\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Kamlesh\Angular2\meantodos\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch (C:\Kamlesh\Angular2\meantodos\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Kamlesh\Angular2\meantodos\node_modules\express\lib\router\layer.js:95:5)
at C:\Kamlesh\Angular2\meantodos\node_modules\express\lib\router\index.js:277:22
at param (C:\Kamlesh\Angular2\meantodos\node_modules\express\lib\router\index.js:349:14)

I'm getting today a similar error related with some mongodb-core update.
I fixed it by forcing mongodb-core to the previous version i had:
npm install --save mongodb-core#1.3.18
Anyway, the first thing you have to check is that req.params.id has a valid hexadecimal 25 char string.

Related

TypeError: User.findOne is not a function

i'm making an api nodejs, and i want to make a login with jwt, i already create the model and the route, i'm testing it on postman with method post, i have a collection called "user" on mongodb but when i send the petition post appear this error `
TypeError: User.findOne is not a function
at E:\AppAgricola\Proyecto\api\routes\loginRoutes.js:8:27
at Layer.handle [as handle_request] (E:\AppAgricola\Proyecto\api\node_modules\express\lib\router\layer.js:95:5)
at next (E:\AppAgricola\Proyecto\api\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (E:\AppAgricola\Proyecto\api\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (E:\AppAgricola\Proyecto\api\node_modules\express\lib\router\layer.js:95:5)
at E:\AppAgricola\Proyecto\api\node_modules\express\lib\router\index.js:281:22
at Function.process_params (E:\AppAgricola\Proyecto\api\node_modules\express\lib\router\index.js:335:12)
at next (E:\AppAgricola\Proyecto\api\node_modules\express\lib\router\index.js:275:10)
at Function.handle (E:\AppAgricola\Proyecto\api\node_modules\express\lib\router\index.js:174:3)
at router (E:\AppAgricola\Proyecto\api\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (E:\AppAgricola\Proyecto\api\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (E:\AppAgricola\Proyecto\api\node_modules\express\lib\router\index.js:317:13)
at E:\AppAgricola\Proyecto\api\node_modules\express\lib\router\index.js:284:7
at Function.process_params (E:\AppAgricola\Proyecto\api\node_modules\express\lib\router\index.js:335:12)
at next (E:\AppAgricola\Proyecto\api\node_modules\express\lib\router\index.js:275:10)
at app.use (E:\AppAgricola\Proyecto\api\app.js:27:5)`
i send user and password field on postman
var express = require('express');
var router = express.Router();
var User = require('../models/user');
var jwt = require('jsonwebtoken');
router.post('/login', function(req, res, next) {
let promise= User.findOne({username:req.body.username}).exec();
promise.then(function(doc){
if(doc){
if(doc.isValid(req.body.password)){
let token = jwt.sign({username:doc.username}, 'secret', {expiresIn: '3h'});
return res.status(200).json(token);
}else{
return res.status(501).json({message: 'invalid credentials'});
}
}else{
return res.status(501).json({message:'User email is not registered'})
}
});
promise.catch(function(err){
return res.status(501).json({message:'some internal error'})
})
})
module.exports = router;
this is the model
var mongoose= require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt');
var schema = new Schema({
username:{type:String, require:true},
password:{type:String, require:true},
//creation_dt:{type:String, require:true}
},
);
schema.statics.hashPassword = function hashPassword(password){
return bcrypt.hashSync(password, 10);
}
schema.methods.isValid = function(hashedpassword){
return bcrypt.compareSync(hashedpassword, this.password);
}
module.export = mongoose.model('User', schema);
i want that the method post return a jwt
this is the method "isValid" inside the model, like you can see, i have a console.log() that show me the variable "this.password" and "hashedpassword", this variables are equal, and this method must return a boolean=true but return "false", i don't get what happen:
schema.methods.isValid = function(hashedpassword){
console.log(this.password)
console.log(hashedpassword)
var data = bcrypt.compareSync(hashedpassword, this.password);
console.log(data)
return bcrypt.compareSync(hashedpassword, this.password);
}
module.export = mongoose.model('User', schema); doesn't export anything.
Node.js (not ES6) export is:
module.exports = ...;
Whatever at the triple dots is the returning value for 'require' function.
Make sure the export is correct.
this is what worked for me:
module.exports = User = mongoose.model('users', UserSchema);
In my case, I had to change
import User from '../../models/User'; (which was added automatically to the imports by VSCode)
to const User = require('../../models').users;
Hope this helps people with similar case.
Just use console.log(module.exports) like if:
module.exports=User=mongoose.model('User',Schema);
if it prints the schema, then it's working and morover the issue lies in the module.exports only.

Why I'm getting the error :ReferenceError: status is not defined when using body-phraser?

I'm new to node js and when using body-phraser I'm getting the error: ReferenceError: status is not defined. The code is shown below.
when a json is posted to the localhost:3000/ products the following error seems to be rising but i can't figure out why this happens. Does the reference error occur due to an bug in my code:
The error I get is:
ReferenceError: status is not defined
at app.use (/home/marper96/Desktop/node/node-rest-shop/app.js:22:5)
at Layer.handle_error (/home/marper96/Desktop/node/node-rest-shop/node_modules/express/lib/router/layer.js:71:5)
at trim_prefix (/home/marper96/Desktop/node/node-rest-shop/node_modules/express/lib/router/index.js:315:13)
at /home/marper96/Desktop/node/node-rest-shop/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/home/marper96/Desktop/node/node-rest-shop/node_modules/express/lib/router/index.js:335:12)
at next (/home/marper96/Desktop/node/node-rest-shop/node_modules/express/lib/router/index.js:275:10)
at Layer.handle_error (/home/marper96/Desktop/node/node-rest-shop/node_modules/express/lib/router/layer.js:67:12)
at trim_prefix (/home/marper96/Desktop/node/node-rest-shop/node_modules/express/lib/router/index.js:315:13)
at /home/marper96/Desktop/node/node-rest-shop/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/home/marper96/Desktop/node/node-rest-shop/node_modules/express/lib/router/index.js:335:12)
The code I'm using:
router.post('/',(req,res,next) =>{
const product ={
name :req.body.name,
price :req.body.price
};
res.status(201).json({
messsage:'Handelling post requests to /products',
createdproduct:product
});
});
module.exports =router;
Please add body-parsor to the router like below lines,
const router = require("express").Router();
const bodyParser = require("body-parser");
router.use(bodyParser.json());
You have to add body-parser to the middle-ware with 'use' method like above and your code,
router.post('/',(req,res,next) =>{
const product ={
name :req.body.name,
price :req.body.price
};
res.status(201).json({
messsage:'Handelling post requests to /products',
createdproduct:product
});
});

element.find is not a function

I'm learning how to make a REST Api and copied the tutorial's code in exactly, but it's giving me this error:
TypeError: Bear.find is not a function
at /Users/madisontaskett/instaApi/server.js:67:14
at Layer.handle [as handle_request] (/Users/madisontaskett/instaApi/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/madisontaskett/instaApi/node_modules/express/lib/router/route.js:137:13)
at next (/Users/madisontaskett/instaApi/node_modules/express/lib/router/route.js:131:14)
at Route.dispatch (/Users/madisontaskett/instaApi/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/madisontaskett/instaApi/node_modules/express/lib/router/layer.js:95:5)
at /Users/madisontaskett/instaApi/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/madisontaskett/instaApi/node_modules/express/lib/router/index.js:335:12)
at next (/Users/madisontaskett/instaApi/node_modules/express/lib/router/index.js:275:10)
at /Users/madisontaskett/instaApi/server.js:35:5
Here's my code snippet:
.get(function(req, res) {
var Bear = require('./api/models/instaApiModel');
Bear.find(function(err, bears) {
if (err)
res.render(err);
res.json(bears);
});
});
It looks like the problem is about loading the Bear Model.
// Bear models lives here
var Bear = require('./app/models/bear');
You also need to make sure that you create a model as follows:
// app/models/bear.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BearSchema = new Schema({
name: String
});
module.exports = mongoose.model('Bear', BearSchema);
Please refer to this link for complete source code.

TypeError using the jwt-express package

I just tried to work with the JWT-Express package for NodeJS in order to create a JWT token when a user wants to log in. Unfortunately, I receive a TypeError with the package.
Following my code:
var express = require('express');
var app = express();
var jwt = require('jwt-express');
app.use(jwt.init('secret'));
app.get('/login', function(req, res) {
var user = {
first: "Firstname",
last: "Lastname",
is_admin: true
};
// we are using cookies so the JWT is
// automatically stored for us
var jwt = res.jwt({
admin: user.is_admin,
name: user.first + ' ' + user.last
});
// we now have access to the JWT Object
console.log(jwt);
// if we weren't using cookies, we could
// now send the token to the client
res.send(jwt.token);
});
app.listen(8080);
I verified that both the object jwt in line 3 and the call to jwt.init returns something unequal to undefined.
The error seems to stick somehow in the package internally. The system crashes even before the GET requests is being processed.
The error is:
TypeError: Cannot read property 'jwt-express' of undefined
at Object.<anonymous> (/Users/stuckenholz/auth/node_modules/jwt-express/jwt-express.js:218:36)
at Layer.handle [as handle_request] (/Users/stuckenholz/auth/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/stuckenholz/auth/node_modules/express/lib/router/index.js:317:13)
at /Users/stuckenholz/auth/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/Users/stuckenholz/auth/node_modules/express/lib/router/index.js:335:12)
at next (/Users/stuckenholz/auth/node_modules/express/lib/router/index.js:275:10)
at expressInit (/Users/stuckenholz/auth/node_modules/express/lib/middleware/init.js:40:5)
at Layer.handle [as handle_request] (/Users/stuckenholz/auth/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/stuckenholz/auth/node_modules/express/lib/router/index.js:317:13)
at /Users/stuckenholz/auth/node_modules/express/lib/router/index.js:284:7
Any ideas?
Best regards...
I had the same error and it happened that I had forgotten to include jwt options.
This solved it for me:
options = { cookies: false }
app.use(jwt.init('secret', options))
I am not using cookies
It looks like the req.cookies is empty at line 218:
token = req.cookies[this.options.cookie];
Don't forget to parse the cookies before initializing jwt-express:
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
https://github.com/expressjs/cookie-parser

express4 passport desirializeuser TypeError: hex is not a function

I tried nodejs login tutorial using passport.
deserializeUser is working well when hosted by c9.io
But hosted by openshift it makes error
TypeError: hex is not a function
at Function.from (native)
at Function.from (native)
at new ObjectID (/opt/app-root/src/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/objectid.js:52:32)
at ObjectID (/opt/app-root/src/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/objectid.js:31:42)
at /opt/app-root/src/app.js:120:17
at pass (/opt/app-root/src/node_modules/passport/lib/authenticator.js:347:9)
at Authenticator.deserializeUser (/opt/app-root/src/node_modules/passport/lib/authenticator.js:352:5)
at SessionStrategy.authenticate (/opt/app-root/src/node_modules/passport/lib/strategies/session.js:53:28)
at attempt (/opt/app-root/src/node_modules/passport/lib/middleware/authenticate.js:348:16)
at authenticate (/opt/app-root/src/node_modules/passport/lib/middleware/authenticate.js:349:7)
at Layer.handle [as handle_request] (/opt/app-root/src/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/opt/app-root/src/node_modules/express/lib/router/index.js:312:13)
at /opt/app-root/src/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/opt/app-root/src/node_modules/express/lib/router/index.js:330:12)
at next (/opt/app-root/src/node_modules/express/lib/router/index.js:271:10)
at initialize (/opt/app-root/src/node_modules/passport/lib/middleware/initialize.js:53:5)
My deserializeUser code is like this
var express = require("express"),
app = express(),
cookieParser = require("cookie-parser"),
bodyParser = require('body-parser'),
assert = require('assert'),
fs = require("fs"),
XLSX = require("xlsx"),
session = require('express-session'),
MongoStore = require('connect-mongo')(session),
multer = require("multer"),
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
mongodb = require('mongodb'),
ObjectId = require('mongodb').ObjectId;
passport.serializeUser(function(user, done) {
console.log("serialize:%s",user._id);
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
if (!db) {
initDb(function(err){});
}
if (db){
var col = db.collection("users");
col.findOne(ObjectId(id), function(err, user) {
console.log("deserialize:%s",user.username);
return done(err, user);
});
}
});
The line (/opt/app-root/src/app.js:120:17) is
col.findOne(ObjectId(id), function(err, user) {
I think the function ObjectId is not working on openshift environment
Is it a just a bug? why working on c9.io but not on openshift??
I'm getting today a similar error related with some mongodb-core update.
I fixed it by forcing mongodb-core to the previous version i had:
npm install --save mongodb-core#1.3.18

Resources