I am trying to run following code on server
var express = require("express"),
app = express(),
bodyParser = require('body-parser'),
errorHandler = require('errorhandler'),
methodOverride = require('method-override'),
hostname = process.env.HOSTNAME || 'localhost',
port = parseInt(process.env.PORT, 10) || 4004,
publicDir = process.argv[2] || __dirname + '/public';
var exec = require('child_process').exec;
var fs = require('fs');
var mongodb = require('mongodb'),
serverdb = new mongodb.Server('127.0.0.1', 27017, {}),
dbName = new mongodb.Db('prisync', serverdb, {});
var url = "urlinfo";
//Show homepage
app.get("/", function (req, res) {
//res.redirect("/index.html");
console.log("shubham ");
dbName.open(function (error, client){
var collection = new mongodb.Collection(client , url); //line 24 ====
collection.find().limit(20).toArray(function (err, dataObjArr){
var data = '';
var dataArr = [];
var i = dataObjArr.length;
//check for error
if(err){return res.end('error!'+err);}
//Data
if(dataObjArr){
while(i--){
dataArr[i] = dataObjArr[i]._id;
}
data = dataArr.join(' ');
res.render('/index.html',{ returnedData : data });
}else{
res.end();
}
});
});
});
app.get("/search", function (req, res){
console.log("shubham batra");
var pro_name = req.query.name;
var pro_code = req.query.code;
var pro_category = req.query.category;
var pro_brand = req.query.brand;
pro_name = pro_name+"";
pro_code = pro_code+"";
pro_brand = pro_brand+"";
pro_category = pro_category+"";
MongoClient.connect('mongodb://127.0.0.1:27017/prisync', function(err, db) {
if (err) throw err;
console.log("Connected to Database");
var documen = {name:pro_name, code:pro_code , category:pro_category, brand:pro_brand };
//documen = JSON.stringify(documen);
//insert record
db.collection('urlinfo').insert(documen, function(err, records) {
if (err) throw err;
});
res.redirect("/index.html");
});
});
//Search page
app.use(methodOverride());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(publicDir));
app.use(errorHandler({
dumpExceptions: true,
showStack: true
}));
console.log("Server showing %s listening at http://%s:%s", publicDir, hostname, port);
app.listen(port);
but it gives following error while try to load localhost:4004
Server showing /home/shubham/Music/pricesync/server/public listening at http://localhost:4004
shubham
/home/shubham/node_modules/mongodb/lib/server.js:274
process.nextTick(function() { throw err; })
^
Error: collection name must be a String
at Error (<anonymous>)
at checkCollectionName (/home/shubham/node_modules/mongodb/lib/utils.js:69:11)
at new Collection (/home/shubham/node_modules/mongodb/lib/collection.js:57:3)
at /home/shubham/Music/pricesync/server/server.js:24:24
at /home/shubham/node_modules/mongodb/lib/db.js:221:5
at connectHandler (/home/shubham/node_modules/mongodb/lib/server.js:272:7)
at g (events.js:180:16)
at emit (events.js:95:17)
at /home/shubham/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:399:23
at /home/shubham/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:756:13
I had the same error, for me it was caused by my timestamp being incorrectly placed.
INCORRECT CODE:
}),{timestamps:true});
CORRECTED CODE:
var mongoose = require('mongoose');
var ObjectId = mongoose.Schema.Types.ObjectId;
var User = mongoose.model('User', new mongoose.Schema({
email:{type:String, required:true},
password:{type:String, required:true},
listings:[{type:ObjectId,ref:"Listings"}]
},{timestamps:true}));
Assuming the collection name is in 'url' varialbe (i.e. 'urlinfo'), the right way to instantiate the collection would be:
var collection = dbName.collection(url); //line 24
If you look at documentation, it states specifically that Collection class should not be instantiated directly : https://mongodb.github.io/node-mongodb-native/api-generated/collection.html
I got stuck at the same situation, while solving the exercise from Guillermos Smashing Node.JS book...
I followed Richard Andreus directions and after few attempts, succesfully established the server.
I newly defined
var Db = require('mongodb').Db,
Server = require('mongodb').Server;
instead of existing variable definitions.
As next I've defined the variable db.
var db = new Db('test', new Server('localhost', 27017));
Then open the connection to db, or in your case dbName.
db.open(function(err, db) {
var collection = db.collection(url);
// in my case I defined app.users instead of collection
NOTE: Don't forget your definition at dbName
Related
I have root endpoint who work when users enter the url like this:
http://localhost:8000/?date=2019-10-20&station=41027&daysForward=3
I want to create second root endpoint in the same file with different query but that did not work.
My code:
// Create express app
var express = require("express")
var app = express()
var mysql = require('mysql')
var express = require("express")
var cors = require('cors')
app.use(cors())
// Server port
var HTTP_PORT = 8000
// Start server
app.listen(HTTP_PORT, () => {
console.log("Server running on port %PORT%".replace("%PORT%",HTTP_PORT))
});
var con = mysql.createConnection({
host: "192.168.1.1",
port: "3456",
user: "user",
password: "pass"
});
var con2 = mysql.createConnection({
host: "192.168.1.1",
port: "3456",
user: "user",
password: "pass"
});
let aladinModel= '';
let aladinModelStations = '';
app.route('/')
.get(function(req, res) {
// omitted
res.setHeader('Access-Control-Allow-Origin', '*');
const date = req.query.date;
const station = req.query.station;
const daysForward = req.query.daysForward;
try {
const query = `CALL aladin_surfex.Get_mod_cell_values_meteogram('${date}', ${station}, ${daysForward})`;
con.query(query, function (err, result, fields) {
if (err) throw err;
aladinModel = result;
});
res.json({aladinModel})
} catch(error){
console.log("Error query database!!!");
}
});
app.route('/stations')
.get(function(req, res) {
// omitted
res.setHeader('Access-Control-Allow-Origin', '*');
try {
const query2 = `SELECT Station,Ime FROM stations_cells`;
con2.query2(query2, function (err, result2, fields) {
if (err) throw err;
aladinModelStations = result2;
});
res.json({aladinModelStations})
} catch(error){
console.log("Error query database!!!");
}
});
app.use(function(req, res){
res.status(404);
});
I guess this is not the right way to route pages but I hope someone can explain to me with an example how I could fix the code - so when a user enters:
http://localhost:3000/stations
the data should be loaded.
I see this error when I try to open this link.
[nodemon] starting `node server.js localhost:8000`
Server running on port 8000
Error query database!!!
This query
SELECT station, ime
FROM stations_cells
on the second root point is fine. I try to SELECT with HeidiSQL and database return the data values ?
Where is the problem for the second root point ?
That might not be the case, but here's the suggestion (which doesn't fit in comment section)
app.route('/')
.get(function(req, res) {
// omitted
});
app.route('/stations')
.get(function(req, res) {
// omitted
});
I'm trying to build REST API with Node.js, Express and Mongodb. I'm using mongodb npm package to connect to the database, below is my sever.js file code
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var port = process.env.PORT || 8080;
var mongo = require("mongodb");
var Server = mongo.Server;
var Db = mongo.Db;
var ObjectID = mongo.ObjectID;
try{
var config = require('./configure.js');
}catch(e){
console.log("configuration file is hidden on github for security");
config = null;
}
var usersCollection = config.usersCollection;
var login = require('./routes/login/index.js');
var signup = require('./routes/signup/index.js');
var Database = new Db(process.env.DBNAME || config.DBNAME , new Server(process.env.DBHOST || config.DBHOST, process.env.DBPORT || config.DBPORT, {'native_parser': true}));
Database.open(function (err, mongoclient) {
if(err){
console.log("Failed to connect to the database. Please Check the connection");
throw err;
}else{
Database.authenticate(process.env.DBUSER || config.DBUSER, process.env.DBPASS || config.DBPASS, function(err, res) {
if (err) {
console.log("Authentication Failed");
throw err;
}else{
console.log("Connected to the database Successfully");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var users = Database.collection(usersCollection);
login(app,users);
signup(app,users);
Database.close();
}
});
}
});
app.listen(port,function(){
console.log("Server Started Listening to port : "+port);
});
routes/login/index.js
module.exports = function(app,users){
app.route('/login')
.post(function(req,res){
var username = req.body.username;
var password = req.body.password;
var query = {'FirstName':username};
users.find().toArray(function(err,docs){
if(err){
throw err;
}else{
console.log("no err");
if(doc.LastName == password){
res.send({status : true});
}else{
res.send({status : false});
}
}
});
});
}
and routes/signup/index.js
module.exports = function(app,users){
app.route('/signup')
.post(function(req,res){
var doc = { EmpNo:"1",
FirstName:"Andrew",
LastName:"Neil",
Age:"30",
Gender:"Male",
Skill:"MongoDB",
Phone:"408-1234567",
Email:"Andrew.Neil#gmail.com",
Salary:"80000"
};
users.insert(doc,function(err,info){
if(err){
throw err;
}else{
console.log('Successfully inserted ' + JSON.stringify(info));
res.send({result: 'done'});
}
});
});
}
When i'm trying to insert documents in server.js , i'm able to insert them successfully but through routes/signup/index.js i'm getting instance pool was destroyed similarly if i try to find the documents in server.js no error but if i try to do it from routes/login/index.js then i'm getting error as topology was destroyed.
Need help to resolve it.
Those errors are thrown if connection is somehow cut in the middle of the process.
Because both users.find() and users.insert() functions are async your server.js file reaches to the Database.close() function and closes the connection to your database before it finishes the process thus giving the errors.
I'm currently developing an Ionic application and writing the server in NodeJS with Express and hosting it on Heroku. However, it doesn't correctly post the desired route. I get this error when I test it on Chrome:
Failed to load resource: the server responded with a status of 404 (Not Found) https://[SERVER NAME].herokuapp.com/rooms//messages
The server should be posting the id parameter in between /rooms/ and /messages/, but it isn't. Here's the server-side code:
var messages = []; //make an array to hold messages
var rooms = [];
app.get('/rooms', function(req, res) {
res.json(rooms);
});
app.get('/rooms/:id/', function(req, res){
var room = rooms[req.params.id];
res.json(room);
});
app.post('/rooms', function(req, res) {
var newRoom = {
timestamp: new Date()
//username: req.body.username
};
rooms.push(newRoom);
res.json(rooms);
console.log(rooms);
});
app.get('/messages', function(req, res) { //req = request, res = response
res.json(messages);
});
app.get('/messages/:id', function(req,res) {
var message = messages[req.params.id];
res.json(message);
});
app.post('/messages', function(req,res){
var newMessage = {
message:req.body.message,
username:req.body.username,
timestamp: new Date()
};
messages.push(newMessage);
res.json(messages);
});
Why isn't it properly posting the correct route? When I check the logs on Heroku it does not appear to be getting the :id for the rooms.
Thank you.
EDIT: Here are the github repos for further reference:
Client: https://github.com/dukeeagle/ttt-client
Server: https://github.com/dukeeagle/ttt-server
I fixed it!
Here's the correct routing method for those who are interested:
app.get('/rooms', function(req, res) { //req = request, res = response
var user = users[req.params.id];
var userRooms=[];
res.json(rooms);
});
app.get('/rooms/:id', function(req,res) {
var room = rooms[req.params.id];
res.json(room);
});
app.post('/rooms', function(req,res){
var newRoom = {
name:req.body.name,
id:rooms.length,
username:req.body.username,
timestamp: new Date(),
messages: [],
players: []
};
rooms.push(newRoom);
res.json(rooms);
});
app.post('/rooms/:id/messages', function(req, res){
var room = rooms[req.params.id];
var newMessage = {
username:req.body.username,
timestamp: new Date(),
message: req.body.message
}
room.messages.push(newMessage);
res.json(room);
});
app.post('/rooms/:id/players', function(req, res){
var room = rooms[req.params.id];
var newPlayer = {
timestamp: new Date(),
player: req.body.username
};
room.players.push(newPlayer);
res.json(room);
});
I init express server with that code:
var express = require('express');
var app = express();
app.get('/rooms/:id/messages', function (req, res) {
var id = req.params.id;
res.send('Hello, moto! ' + id);
});
app.listen(2345, function () {
console.log('server started');
});
When I navigate to http://localhost:2345/rooms/123/messages I see at the page string Hello, moto! 123
Try to remove your other routes for tests, maybe it is get some conflicts.
When i run my code i get an error
What i'm trying to do is when someone logs on to my site it logs the IP and other data into a database. it seems to work but then i get this error and it exits out of my app
{ [Error: Trying to open unclosed connection.] state: 1 }
Connection to database has been established
/home/azura/node_modules/mongoose/lib/index.js:343
throw new mongoose.Error.OverwriteModelError(name);
^
OverwriteModelError: Cannot overwrite `dataType` model once compiled.
at Mongoose.model (/home/azura/node_modules/mongoose/lib/index.js:343:13)
at Namespace.<anonymous> (/home/azura/Desktop/dbWrite.js:19:37)
at Namespace.EventEmitter.emit (events.js:95:17)
at Namespace.emit (/home/azura/node_modules/socket.io/lib/namespace.js:205:10)
at /home/azura/node_modules/socket.io/lib/namespace.js:172:14
at process._tickCallback (node.js:415:13)
The code that im using is:
var mongoose = require("mongoose");
var express = require("express");
var app = express();
var http = require("http").Server(app);
var io = require("socket.io")(http);
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
});
io.on("connection", function (socket) {
var ip = socket.request.socket.remoteAddress;
var dataBase = mongoose.connection;
mongoose.connect("mongodb://localhost:27017/NEW_DB1");
dataBase.on("error", console.error);
console.log("Connection to database has been established");
var collectedData = new mongoose.Schema({
ipAddress: String,
time: Number
});
var collectionOfData = mongoose.model("dataType", collectedData);
var Maindata = new collectionOfData({
ipAddress: ip,
time: 100000000000000000
});
Maindata.save(function (err, Maindata) {
if (err) {
return console.error(err);
} else {
console.dir(Maindata);
}
});
});
http.listen(10203, function () {
console.log("Server is up");
});
the index.html file has nothing important on it.
I'm just wondering why i'm getting this error.
what can i do to fix it?
Put this code out of connection scope. No Need to create Schema every type there is new connection event.
mongoose.connect("mongodb://localhost:27017/NEW_DB1");
dataBase.on("error", console.error);
console.log("Connection to database has been established");
var collectedData = new mongoose.Schema({
ipAddress: String,
time: Number
});
var collectionOfData = mongoose.model("dataType", collectedData);
io.on("connection", function (socket) {
var ip = socket.request.socket.remoteAddress;
var dataBase = mongoose.connection;
var Maindata = new collectionOfData({
ipAddress: ip,
time: 100000000000000000
});
Maindata.save(function (err, Maindata) {
if (err) {
return console.error(err);
} else {
console.dir(Maindata);
}
});
});
every time a connection come in then the "connection" event will be emit,so
mongoose.connect("mongodb://localhost:27017/NEW_DB1");
will execute manny times,this cause the error.
I have an iOS app which is sending a JSON packet to a webserver. The webserver code looks like this:
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
console.log("MongoDB connection is open.");
});
// Mongoose Schema definition
var Schema = mongoose.Schema;
var LocationSchema = new Schema({
X: Number,
Y: Number,
Orientation: Number,
UserID: String,
Time: String
});
// Mongoose Model definition
var LocationsCollection = mongoose.model('locations', LocationSchema);
// create application/json parser
var jsonParser = bodyParser.json();
// URL management
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.post('/update', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
else {
console.log(req.body);
}
});
// Start the server
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('App listening at %s:%s',host, port)
});
The key part is the app.post method which processes the incoming http request being sent from my iOS app. At the moment, the method which prints the req.body to the console looks like this:
{
datapoint_1:
{ timestamp: '2015-02-06T13:02:40:361Z',
x: 0.6164286615466197,
y: -0.6234909703424794,
id: 'B296DF8B-6489-420A-97B4-6F0F48052758',
orientation: 271.3345946652066 },
datapoint_2:
{ timestamp: '2015-02-06T13:02:40:961Z',
x: 0.6164286615466197,
y: -0.6234909703424794,
id: 'B296DF8B-6489-420A-97B4-6F0F48052758',
orientation: 273.6719055175781 }
}
So, you can see the request is a nested JSON object. Ideally, I'd like to loop through the request objects (ie. the datapoints) and insert those into the mongoDB database (via mongoose). However, I can't seem to figure out how to do much of anything with the req.body. I can't seem to create a loop to iterate through the request or how to properly parse the nested JSON file so it matches the mongoose schema. Can anyone provide some guidance on how to insert these datapoints into the mongoose database?
Set body-parser's extended property to true to allow parsing nested objects.
var express = require('express');
var app = express()
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
Answering my own question. But, after figuring out how to access the key/value pairs inside the nested JSON object... it became relatively easy to figure out the rest. The updated app.post function now looks like this:
app.post('/update', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
else {
for(var datapoint in req.body){
//create new instance of LocationCollection document
var point = new LocationsCollection({
X:Number(req.body[datapoint]["x"]),
Y:Number(req.body[datapoint]["y"]),
Orientation:Number(req.body[datapoint]["orientation"]),
Time:req.body[datapoint]["timestamp"],
UserID:req.body[datapoint]["id"]
});
//insert the newly constructed document into the database
point.save(function(err, point){
if(err) return console.error(err);
else console.dir(point);
});
}
}
});
I can test if this worked by putting the following method inside the callback function once the mongodb connection is first established:
//Find all location points and print to the console.
console.log("Searching for all documents in Location Points Collection");
LocationsCollection.find(function(err,data){
if(err) console.error(err);
else console.dir(data);
});
This will print any documents that have been previously added to the database. Hopefully this helps.
Try somthing like this.
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json({limit:1024*1024, verify: function(req, res, buf){
try {
JSON.parse(buf);
} catch(e) {
res.send({
error: 'BROKEN_JSON'
});
}
}}));
It should be a simple for (var key in obj) loop:
app.post('/update', jsonParser, function (req, res) {
var locationObject = req.body(),
insertObjects = [],
key;
for (key in locationObject) { // loop through each object and insert them into our array of object to insert.
insertObjects.push(locationObject[key]);
}
if (!insertObjects.length) { // if we don't have any object to insert we still return a 200, we just don't insert anything.
return res.status(200).send({
success: true,
message: 'Nothing inserted, 0 locations in POST body',
count: 0;
});
}
LocationsCollection.create(insertObjects, function (err, res) {
if (err) {
return res.status(400).send({
success: false,
message: err.message
});
}
// we have successfully inserted our objects. let's tell the client.
res.status(200).send({
success: true,
message: 'successfully inserted locations',
count: insertObjects.length;
});
});
});
Mongo allows for inserting multiple documents with a single callback, which makes this a lot easier.
This also checks the schema to ensure only proper documents are created.