element.find is not a function - node.js

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.

Related

Express - Cannot access 'Database' before initialization

const express = require('express');
const upload = require("express-fileupload");
const editJsonFile = require("edit-json-file");
const fs = require('fs');
const app = express();
app.use(upload())
app.use(express.urlencoded({ extended: true }))
const playlist = editJsonFile(`${__dirname}/playlist.json`);
app.post("/upload", (req, res) => {
//Save file from the html form to ./mp3
var file = req.files.file;
req.pipe(fs.createWriteStream("./mp3/" + file.name));
res.send("File uploaded");
playlist.append("playlist", file.name)
playlist.save()
}),
app.get("/playlist", (req, res) => {
console.log(playlist.get("playlist"))
let playlist = playlist.get("playlist")
let html = "";
for (let i = 0; i < playlist.length; i++) {
html += `<br>${playlist[i]}`;
}
res.send(html);
}),
Hey,
Im trying to make a music player, but somehow I get the error:
ReferenceError: Cannot access 'playlist' before initialization
at C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\index.js:20:17
at Layer.handle [as handle_request] (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\index.js:284:15
at Function.process_params (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\index.js:346:12)
at next (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\index.js:280:10)
at urlencodedParser (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\body-parser\lib\types\urlencoded.js:91:7)
at Layer.handle [as handle_request] (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\layer.js:95:5)
I can write to the Database without any issues, but when I try to read from it I get the error above, what can I do?
app.get("/playlist", (req, res) => {
console.log(playlist.get("playlist"))
let playlist = playlist.get("playlist")
The second line console.log(playlist.get("playlist")) is trying to print the playlist variable but its declared in the next line, hence no access to that particular variable ergo the error. You can only access something after it has been initialized.
I think you are overwriting the playlist variable. The file is playlist and when you get the element you assign it to playlist as well
Also, a file is not a database

while inserting data to database using postman showing error in controller file

while using node.js i am not able to insert a data to database ,i am using express.js ,mongoose but getting error which i mentioned in code as comment
Blockquote
error is
Blockquote
TypeError: Cannot read property 'name' of undefined
at insert (E:\node\website\controller\signup.js:5:25)
at Layer.handle [as handle_request] (E:\node\website\node_modules\express\lib\router\layer.js:95:5)
at next (E:\node\website\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (E:\node\website\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (E:\node\website\node_modules\express\lib\router\layer.js:95:5)
at E:\node\website\node_modules\express\lib\router\index.js:281:22
at Function.process_params (E:\node\website\node_modules\express\lib\router\index.js:335:12)
at next (E:\node\website\node_modules\express\lib\router\index.js:275:10)
at Function.handle (E:\node\website\node_modules\express\lib\router\index.js:174:3)
at router (E:\node\website\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (E:\node\website\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (E:\node\website\node_modules\express\lib\router\index.js:317:13)
at E:\node\website\node_modules\express\lib\router\index.js:284:7
at Function.process_params (E:\node\website\node_modules\express\lib\router\index.js:335:12)
at next (E:\node\website\node_modules\express\lib\router\index.js:275:10)
at expressInit (E:\node\website\node_modules\express\lib\middleware\init.js:40:5)
at Layer.handle [as handle_request] (E:\node\website\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (E:\node\website\node_modules\express\lib\router\index.js:317:13)
at E:\node\website\node_modules\express\lib\router\index.js:284:7
at Function.process_params (E:\node\website\node_modules\express\lib\router\index.js:335:12)
at next (E:\node\website\node_modules\express\lib\router\index.js:275:10)
at query (E:\node\website\node_modules\express\lib\middleware\query.js:45:5)
Blockquote
//controller file named as signup.js
var express=require('express');
var post1=require('../model/singup')
var router=express.Router();
var insert=(req,res)=>{
var name1= req.body.name;// error:name is not defined
var email1= req.body.email;//error:email is not defined
var password1= req.body.password;//error:password is not defined
post1.create({
name: name1,email:email1,password:password1
},(err,result)=>{
if(err){res.json({message:'error'
})
}
else{res.json({message:'sucessful',result:result
})
}
})
}
router.post('/signup',insert);
router.get('/h',(req,res)=>{
res.json({
message:'insert'
})
console.log("insert");
})
module.exports=router;
Blockquote
//model file named as signup.js
require('../db');
var mongoose=require('mongoose');
mongoose.Promise=require('bluebird');
var schema= new mongoose.Schema({
name:{type:String,required:true},
email:{type:String,required:true},
password:{type:String,required:true},
},
{timestamp:true});
module.exports=mongoose.model('post1',schema);
Blockquote
//db.js file for database connection
var mongose=require('mongoose');
mongose.set('useNewUrlParser', 'true');
mongose.set('useCreateIndex', 'true');
mongose.set('useFindAndModify', 'true');
mongose.connect("mongodb://127.0.0.1:27017/website");
var db=mongose.connection;
db.on('error',console.error.bind(console,'connection error'));
db.once('open',(req,res)=>{
console.log("connected with db!!!");
})
Blockquote
//index.js
var app=require('./server')
var signup=require('./controller/signup')
var session=require('express-session')
app.set('viewengin','ejs')
app.set('useNewUrlParser', 'true')
app.set('useUnifiedTopology', 'true')
app.use('/user',signup)
app.use(session({
secret:'keyboard cat ',
resave:false,
cookies:{
secrue:true
},
}))
app.all('*',(req,res)=>{
return res.json({status: 205,message: 'not found'});
})
var server=app.get('/',(req,res)=>{
req.end()
});
Seems you are missing the body-parser middleware.
$ npm i body-parser
var express=require('express');
var bodyParser = require('body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

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.

Expressjs Routes based on an Array of objects

Trying to setup routes based on an array of objects in ExpressJS, but I'm getting an error when attempting to access the route.
The error is this:
TypeError: shares[Symbol.iterator] is not a function
at router
(C:\Users\rutherfordc.AA\Documents\GitHub\transientComplete\transient-server\routes\shares.js:10:18)
at Layer.handle [as handle_request] (C:\Users\rutherfordc.AA\Documents\GitHub\transientComplete\transient-server\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\rutherfordc.AA\Documents\GitHub\transientComplete\transient-server\node_modules\express\lib\router\index.js:317:13)
at C:\Users\rutherfordc.AA\Documents\GitHub\transientComplete\transient-server\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\rutherfordc.AA\Documents\GitHub\transientComplete\transient-server\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\rutherfordc.AA\Documents\GitHub\transientComplete\transient-server\node_modules\express\lib\router\index.js:275:10)
at expressInit (C:\Users\rutherfordc.AA\Documents\GitHub\transientComplete\transient-server\node_modules\express\lib\middleware\init.js:40:5)
at Layer.handle [as handle_request] (C:\Users\rutherfordc.AA\Documents\GitHub\transientComplete\transient-server\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\rutherfordc.AA\Documents\GitHub\transientComplete\transient-server\node_modules\express\lib\router\index.js:317:13)
at C:\Users\rutherfordc.AA\Documents\GitHub\transientComplete\transient-server\node_modules\express\lib\router\index.js:284:7
from code like this:
var router = (shares) => {
for(let share of shares){
shareRouter.route(`/${share.name}`)
.get((req, res) => {
var fileList = [];
fs.readdir(share.location, (err, files) => {
for(let file in files){
fileList.push(file);
shareRouter.route(`/${file}`)
.get((req, res) => {
var filePath = path.join(share.location, file);
res.download(filePath, `${file}`);
});
}
}).then(()=>{
res.render('shareFiles', fileList);
});
});
}
};
shares is defined prior to the router function call. What's supposed to happen is that when the application starts, it looks in the config file, imported earlier, get's the list of folders to share and sets them up based on the name property of the object, then goes through each of the files in the folder to create routes based on their file names, which is then passed into a pug template that provides links to the file routes.

Select document by _id accessing database from MongoDB MLAB in 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.

Resources