I tried connecting it with mlab database but its not working, went through a lot of stackoverflow answers and tried everything but the errors are still there, please help.
var express = require('express');
var mongojs = require('mongojs');
var mongodb = require('mongodb');
// var db = mongojs('contactlist',['contactlist']);
var uri = 'mongodb://user:pass#####.mlab.com:13702/contactlist'
mongodb.MongoClient.connect(uri, { server: { auto_reconnect: true } }, function (err, contactlist) {
});
var db = mongodb.connect(uri);
var app = express();
var bodyParser = require('body-parser');
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
app.get('/contactlist', function(req, res){
console.log("I received a GET request");
db.contactlist.find(function(err, docs){
console.log(docs);
res.json(docs);
});
});
app.post('/contactlist', function(req, res) {
console.log(req.body);
db.contactlist.insert(req.body,function(err,doc) {
res.json(doc);
});
});
app.listen(process.env.PORT ||3000, function(){
console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});
I am getting these errors after I try inserting data on the browser, its not even displaying the data from the database.
Errors:
TypeError: Cannot read property 'find' of undefined
at D:\contactlistapp\server.js:17:16
at Layer.handle [as handle_request] (D:\contactlistapp\node_modules\express\lib\router\layer.js:95:5)
at next (D:\contactlistapp\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (D:\contactlistapp\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (D:\contactlistapp\node_modules\express\lib\router\layer.js:95:5)
at D:\contactlistapp\node_modules\express\lib\router\index.js:281:22
at Function.process_params (D:\contactlistapp\node_modules\express\lib\router\index.js:335:12)
at next (D:\contactlistapp\node_modules\express\lib\router\index.js:275:10)
at jsonParser (D:\contactlistapp\node_modules\body-parser\lib\types\json.js:103:7)
at Layer.handle [as handle_request] (D:\contactlistapp\node_modules\express\lib\router\layer.js:95:5)
{ name: 'kkm', email: 'kmk' }
TypeError: Cannot read property 'insert' of undefined
at D:\contactlistapp\server.js:27:16
at Layer.handle [as handle_request] (D:\contactlistapp\node_modules\express\lib\router\layer.js:95:5)
at next
db.[collection_name] syntax ( ie. collection name on property ) is supported in MongoShell, but in node environment you must use following syntax:
db.collection("collection_name").find(). The same with insert.
Also note that connect function of MongoClient is async. You must get reference to database from callback that you specified.
mongodb.MongoClient.connect(uri, { server: { auto_reconnect: true } }, function (err, contactlist) {
db = contactlist;
});
Related
Server error while connecting to mongoDB
TypeError: db.collection is not a function
at /Users/prokhorov/Desktop/IOS DEV /Shop/Shop/server.js:9:8
at Layer.handle [as handle_request] (/Users/prokhorov/Desktop/IOS DEV /Shop/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/prokhorov/Desktop/IOS DEV /Shop/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/prokhorov/Desktop/IOS DEV /Shop/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/prokhorov/Desktop/IOS DEV /Shop/node_modules/express/lib/router/layer.js:95:5)
at /Users/prokhorov/Desktop/IOS DEV /Shop/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/prokhorov/Desktop/IOS DEV /Shop/node_modules/express/lib/router/index.js:335:12)
at next (/Users/prokhorov/Desktop/IOS DEV /Shop/node_modules/express/lib/router/index.js:275:10)
at expressInit (/Users/prokhorov/Desktop/IOS DEV /Shop/node_modules/express/lib/middleware/init.js:40:5)
at Layer.handle [as handle_request] (/Users/prokhorov/Desktop/IOS DEV /Shop/node_modules/express/lib/router/layer.js:95:5)
The first time I came across the need to use Node.js. Hope you can help. thanks
This is the code for my server.js file
var MongoClient = require('mongodb').MongoClient;
var app = express();
var db;
app.get('/', function(req, res) {
db.collection('product').find().toArray(function (err, docs) {
if (err) {
console.log(err);
return res.sendStatus(500);
}
res.send(docs);
})
})
MongoClient.connect('mongodb+srv://test:password#cluster0.jatcp.mongodb.net/myFirstDatabase?retryWrites=true&w=majority', function (err, database) {
if (err) {
return console.log(err);
}
db = database;
app.listen(3012, function () {
console.log('API app started');
})
})
you can try this I think this should work. I try it locally here is the sample code
const express = require('express');
const app = express();
let MongoClient = require('mongodb').MongoClient;
var db;
MongoClient.connect('mongodb://localhost:27017', function (err, client) {
if (err) throw err;
db = client.db('DatabaseName');
app.listen(3000);
});
app.get('/', (req, res) => {
db.collection('CollectionName')
.find()
.toArray(function (err, result) {
if (err) throw err;
res.send(result);
});
});
I am getting the following error while posting the data via REST API through Postman using Node.js. I am providing my code below.
server.js:
var express=require('express');
var morgan = require('morgan');
var http=require('http');
var bodyParser= require('body-parser');
var methodOverride = require('method-override');
var mongo = require('mongojs');
var app=express();
var server=http.Server(app);
var port=8080;
require('./route/route.js')(app);
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({ extended: false,limit: '5mb' })) // parse application/x-www-form-urlencoded
app.use(bodyParser.json({limit: '5mb'})) // parse application/json
app.use(methodOverride()); // simulate DELETE and PUT
app.get('/',function(req,res){
res.json({"message": "Task management application."});
})
server.listen(port);
console.log("Server is running on the port"+port);
route/route.js:
var task=require('../controller/controller.js');
module.exports = function(app) {
app.post('/signup',task.userSignup);
}
controller/controller.js:
var mongoJs=require('mongojs');
var database='TASK';
var collections=['f_users'];
var db=mongoJs("127.0.0.1:27017/"+database, collections);
db.on('connect', function () {
console.log('database connected')
});
exports.userSignup=function(req,res){
console.log('req',req);
var username=req.body.username;
var password=req.body.password;
var phone=req.body.phone;
db.f_users.insert({'username':username,'password':password,'phone':phone},function(err,docs){
if (!err) {
if (docs) {
res.json({'message':'User has registered successfully'});
}
}
})
}
I am doing the post like below.
Here I am getting the following error while posting the data.
TypeError: Cannot read property 'username' of undefined
<br> at exports.userSignup (C:\xampp\htdocs\bigdata\controller\controller.js:10:23)
<br> at Layer.handle [as handle_request] (C:\xampp\htdocs\bigdata\node_modules\express\lib\router\layer.js:95:5)
<br> at next (C:\xampp\htdocs\bigdata\node_modules\express\lib\router\route.js:131:13)
<br> at Route.dispatch (C:\xampp\htdocs\bigdata\node_modules\express\lib\router\route.js:112:3)
<br> at Layer.handle [as handle_request] (C:\xampp\htdocs\bigdata\node_modules\express\lib\router\layer.js:95:5)
<br> at C:\xampp\htdocs\bigdata\node_modules\express\lib\router\index.js:277:22
<br> at Function.process_params (C:\xampp\htdocs\bigdata\node_modules\express\lib\router\index.js:330:12)
<br> at next (C:\xampp\htdocs\bigdata\node_modules\express\lib\router\index.js:271:10)
<br> at expressInit (C:\xampp\htdocs\bigdata\node_modules\express\lib\middleware\init.js:33:5)
<br> at Layer.handle [as handle_request] (C:\xampp\htdocs\bigdata\node_modules\express\lib\router\layer.js:95:5)
How can I resolve this error and save the data successfully?
My Code!!
var neo4j = require('neo4j-driver').v1;
var express = require('express');
var logger = require('morgan');
var path = require('path');
var bodyParser =require('body-parser');
var app=express();
app.set('views',path.join(__dirname, 'views'));
app.set('view engine','ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname,'public')));
var driver = neo4j.driver("bolt://localhost:7687", neo4j.auth.basic("Novasys", "123456"));
var session = driver.session();
app.get('/', function(req,res){
session
.run('MATCH (n:Movie) RETURN n LIMIT 30')
.then(function(result){
var moviearr = [];
result.records.forEach(function(record){
moviearr.push({enter code here
id: record._fields[0].identity.low,
title: record._fields[0].properties.title,
released: record._fields[0].properties.released
});
});
session
.run('MATCH (n:Person) RETURN n LIMIT 25')
.then(function(result2){
var personArr = [];
result2.records.forEach(function(record){
personArr.push({
id: record._fields[0].identity.low,
name: record._fields[0].properties.name
});
});
res.render('index', {
movies: moviearr,
persons: personArr
});
})
.catch(function(err){
console.log(err);
});
})
.catch(function(err){
console.log(err);
});
});
app.post('/movie/add',function(req,res,next){
var title = req.body.title;
var released = req.body.released;
session
.run('CREATE(n:Movie {title:{titleParam}, released:{releasedParam}}) RETURN n.title',{titleParam:title, releasedParam:released})
.then(function(result){
res.redirect();
session.close();
})
.catch(function(err){
console.log(err);
});
res.redirect('/');
});
app.listen(4000);
console.log('Server started on port 4000');
module.exports=app; **strong text**
getting error!!
TypeError: Cannot read property 'name' of undefined
at B:\nodejs\newp\app.js:75:30
at Layer.handle [as handle_request] (B:\nodejs\newp\node_modules\express\lib\router\layer.js:95:5)
at next (B:\nodejs\newp\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch (B:\nodejs\newp\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (B:\nodejs\newp\node_modules\express\lib\router\layer.js:95:5)
at B:\nodejs\newp\node_modules\express\lib\router\index.js:277:22
at Function.process_params (B:\nodejs\newp\node_modules\express\lib\router\index.js:330:12)
at next (B:\nodejs\newp\node_modules\express\lib\router\index.js:271:10)
at serveStatic (B:\nodejs\newp\node_modules\serve-static\index.js:75:16)
at Layer.handle [as handle_request] (B:\nodejs\newp\node_modules\express\lib\router\layer.js:95:5)
Can anyone help me in solving this. I am new to node js as well as neo4j.
Thanks in Advance
☼ Hello,
Do you have a label "Person" in your Neo4j database ?
session
.run('MATCH (n:Person) RETURN n LIMIT 25')
Have you tried with :
session
.run('MATCH (n:Actor) RETURN n LIMIT 25')
I think you took this exemple here, but they use the labels "Movies" and "Actors"
trying to implement authentication in my web-app using passport, passport-local and pasport-local-mongoose on node.js (using cloud9).
my authentication is successful, but when i'm trying to redirect to other page within my app (redirecting to http://www.google.com works!) i'm getting this stacktrace (need a direction on this):
TypeError: user.get is not a function
at /home/ubuntu/workspace/attendance/v4/node_modules/passport-local-mongoose/index.js:217:21
at pass (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/authenticator.js:347:9)
at Authenticator.deserializeUser (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/authenticator.js:352:5)
at SessionStrategy.authenticate (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/strategies/session.js:53:28)
at attempt (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/middleware/authenticate.js:348:16)
at authenticate (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/middleware/authenticate.js:349:7)
at Layer.handle [as handle_request] (/home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/index.js:312:13)
at /home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/index.js:330:12)
at next (/home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/index.js:271:10)
at initialize (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/middleware/initialize.js:53:5)
at Layer.handle [as handle_request] (/home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/index.js:312:13)
at /home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/index.js:330:12)
my app.js is the following:
var express = require('express'),
app = express(),
BodyParser = require("body-parser"),
mongoose = require("mongoose"),
students_class = require("./models/class"),
passport= require("passport"),
localstrategy=require ("passport-local"),
// passportlocalmongoose=("passport-local-mongoose"),
student = require ("./models/student");
mongoose.connect("mongodb://localhost/attendance");
app.set("view engine", "ejs");
app.use(express.static ("public"));
app.use(BodyParser.urlencoded({extended: true}));
app.use (require("express-session")( {
secret: "liran",
resave:false,
saveUninitialized:false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new localstrategy(student.authenticate()));
passport.serializeUser(student.serializeUser());
passport.deserializeUser(student.serializeUser());
// ====
// routes
// =====
app.get("/", function(req, res) {
student.find({}, function(err, student) {
if (err) {
console.log(err);
} else {
res.render("home/index.ejs", {
students: student
});
}
});
});
app.post ("/login",passport.authenticate("local"),function (req,res) {
res.redirect("/");
})
and my user model:
var mongoose = require("mongoose"),
passportlocalmongoose=require("passport-local-mongoose")
var studentsSchema = new mongoose.Schema({
username: String,
passport:String
// name: String,
// image: String,
// description:String,
// classes: [{ type: mongoose.Schema.Types.ObjectId, ref: 'class' }]
});
studentsSchema.plugin(passportlocalmongoose);
module.exports= mongoose.model("student", studentsSchema);
Let's check the stack trace to see if we can find a hint:
TypeError: user.get is not a function
at /home/ubuntu/workspace/attendance/v4/node_modules/passport-local-mongoose/index.js:217:21
at pass (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/authenticator.js:347:9)
at Authenticator.deserializeUser (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/authenticator.js:352:5)
...
Hmm, deserializeUser might be causing the problem.
Let's look at how it's set up:
passport.serializeUser(student.serializeUser());
passport.deserializeUser(student.serializeUser());
Perhaps you meant to pass student.deserializeUser() to passport.deserializerUser()?
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
mongoose.connect("mongodb://localhost/test");
var todoschema = new mongoose.Schema ({
name : {type: String, required: true}
});
var todomodel = mongoose.model('todolist',todoschema);
app.get('/',function(req,res){
res.sendFile('C:/Users/Rohit/Desktop/New folder/public/todo.html');
})
app.get('/todolist', function (req, res){
todomodel.find(function(err,tasks){
res.json(tasks);
});
});
app.post('/todolist', function (req, res) {
todomodel.insert(req.body, function(err, task) {
res.json(task);
});
});
app.delete('/todolist/:id', function (req, res) {
todomodel.remove(req.params.id, function (err, task) {
res.json(task);
});
});
app.get('/todolist/:id', function (req, res) {
todomodel.findById(req.params.id, function (err, task) {
res.json(task);
});
});
app.put('/todolist/:id', function (req, res) {
todomodel.findAndModify({
query: req.params.id,
update: {$set: {name: req.body.name}},
new: true}, function (err, task) {
res.json(task);
}
);
});
app.listen(3000);
console.log("Server running on port 3000");
TypeError: path must be absolute or specify root to res.sendFile
at ServerResponse.sendFile (C:\Users\Rohit\node_modules\express\lib\response.js:403:11)
at C:\Users\Rohit\Desktop\New folder\mong.js:17:9
at Layer.handle [as handle_request] (C:\Users\Rohit\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Rohit\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch (C:\Users\Rohit\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\Rohit\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\Rohit\node_modules\express\lib\router\index.js:277:22
at Function.process_params (C:\Users\Rohit\node_modules\express\lib\router\index.js:330:12)
at next (C:\Users\Rohit\node_modules\express\lib\router\index.js:271:10)
at jsonParser (C:\Users\Rohit\node_modules\body-parser\lib\types\json.js:100:40)
at Layer.handle [as handle_request] (C:\Users\Rohit\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\Rohit\node_modules\express\lib\router\index.js:312:13)
at C:\Users\Rohit\node_modules\express\lib\router\index.js:280:7
at Function.process_params (C:\Users\Rohit\node_modules\express\lib\router\index.js:330:12)
at next (C:\Users\Rohit\node_modules\express\lib\router\index.js:271:10)
at expressInit (C:\Users\Rohit\node_modules\express\lib\middleware\init.js:33:5)
I tried to display a todo.html page by connecting to http://localhost:3000 , but I'm getting an error when i open the http://localhost:3000 page , the error i have uploaded above as a snippet. Can you please guide me on how to display the html file ?
res.sendFile("C:/Users/Rohit/Desktop/New folder/public/todo.html");
UPDATE
try to use
res.sendFile("C:\\Users\\Rohit\\Desktop\\New folder\\public\\todo.html");
#robin
look at the express source code, express/lib/utils.js
exports.isAbsolute = function(path){
if ('/' == path[0]) return true;
if (':' == path[1] && '\\' == path[2]) return true;
if ('\\\\' == path.substring(0, 2)) return true; // Microsoft Azure absolute path
};
It only check the \\, i think it is a bug.