I try to build some Web Api to get data from MongodbLab ,I can call the api and reply string now , but can't not get data from mongodb , I follow many tutorial try for three hours , but the web and curl always reply [ empty reply from server ] , I believe is this part have some issue exports.findAll = function(req, res) {...}, please help
code
var express = require('express'),
songs = require('./routes/route');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
app.get('/songs',songs.findAll);
route
var mongoose = require('mongoose');
var mongo = require('mongodb');
var uri = "mongodb://1111:aaaa#ds061365.mongolab.com:61365/aweitest";
mongoose.connect(uri);
// we're connected!
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection errrrrrrrror:'));
db.once('open', function() {
console.log("mongodb is connected!!");
});
exports.findAll = function(req, res) {
db.collection('songs',function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
Related
I'm using nodeJS for the first time, and I'm trying to do an application that connects to MongoDB via Mongoose.
I've installed MongoDB, NodeJS and Mongoose(via npm) successfully.
My problem is:
When I connect my node application through mongoose does not show any error, but when I try to insert a document, it just doesn't do anything at all. Freezes at the save line.
This is my code
var express = require('express');
var app = express();
var mongoose = require('mongoose');
...
mongoose.connect('mongodb://127.0.0.1:27017/exampleDB');
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
var someModel = mongoose.model('someModel', {
name : String
});
app.get('/api/todos', function(req, res) {
var awesome_instance = new someModel({ name: 'awesome' });
console.log("about to save the document");
awesome_instance.save(function (err) {
if (err) return handleError(err);
});
});
app.post('/api/todos', function(req, res) {
});
...
app.listen(8080);
console.log("App listening on port 8080");
Using a mongo client I can see my db, but not the collection that the code should have created. Also my mongoDB detects the connection from nodeJS. I just don't know what could be happening.
This is what my server.js (node) is showing
$ node server.js
App listening on port 8080
about to save the document
GET /api/todos - - ms - -
This is my mongo client
$ ./mongo
MongoDB shell version v4.0.0
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 4.0.0
use exampleDB
switched to db exampleDB
show collections
exampleCollection
Thanks a lot in advance.
Let your get this and see if it works.
var express = require('express');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/exampleDB', { useNewUrlParser: true });
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
var someModel = mongoose.model('someModel', {
name : String
});
app.get('/api/todos', async function(req, res) {
var awesome_instance = new someModel({ name: 'awesome' });
await awesome_instance.save()
});
app.post('/api/todos', function(req, res) {
});
app.listen(8080, ()=>console.log("App listening on port 8080"));
I have a strange issue with MongoDB-mongoose, which does not respond to REST API
mongoose version - 4.11.3
Mongo DB shell version 3.4.6
Everything is local on my computer
Connection to Mongo DB is the following:
server.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("Connected correctly to db");
});
...
var app = express();
var tasks = require('./server/routes/taskRouter');
app.use('/api/tasks',tasks);
The log "Connected correctly to db" is printed.
Schema (tasks.js)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var taskSchema = new Schema({
name: String
});
var Task = mongoose.model('Task', taskSchema);
module.exports = Task;
And finally taskRouter.js
var express = require('express');
var bodyParser = require('body-parser');
var Task = require('../models/tasks');
var taskRouter = express.Router();
taskRouter.use(bodyParser.json());
taskRouter.route('/')
.get(function (req, res, next) {
Task.find({}, function (err, task) {
console.log("result"+task)
if (err) throw err;
res.json(task);
});
})
.post(function (req, res, next) {
var task = new Tasks();
console.log ('the name is '+req.body.name);
task.name = req.body.name;
task.save(function(err){
console.log ("arrived there");
if (err)
res.send(err);
res.json({message: "Task created"});
});
})
As you see, everything is by the book .
But I never get any logs from task.save and Task.find
My 'morgan' logger shows just the following logs:
GET /api/tasks - - ms - -
POST /api/tasks - - ms - -
Postman is stuck on "Loading", until receives a timeout: Could not get any response.
All simple operation on the tasks collection in Mongo DB shell are performed without any problem.
What happens with mongoose?
Thanks in advance.
Try to create a separate file config.js with the following code :
module.exports = {
'database': 'mongodb://localhost:27017/yourdatabasename'
}
server.js:
...
var config = require('./config'); // get our config file
...
var mongoose = require('mongoose');
...
mongoose.connect(config.database, { useMongoClient: true });
mongoose.connection.on('open', function(err, doc){
console.log("connection established");
var app = express();
var tasks = require('./server/routes/taskRouter');
app.use('/api/tasks',tasks);
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("Connected correctly to db");
});
post request a few but I can not make multiple post request or get request
When I write multiple app.post() or app.get I get error this error :
Assertion error :(function) is required How to fix this problem thnks all of you...
APPjs
var restify = require('restify');
var config = require('./config');
var app = restify.createServer({name:'REST-api'});
app.use(restify.fullResponse());
app.use(restify.bodyParser());
app.use(restify.queryParser());
app.listen(config.port, function() {
console.log('server listening on port number', config.port);
});
var routes = require('./routes')(app);
Route.JS
module.exports.my = function(app) {
var user = require('./controllers/userController');
var location=require('./controllers/locationController');
var ilan=require('./controllers/ilanController');
app.get('/', function(req, res, next) {
return res.send("WELCOME TO REST API");
});
//User get and create
app.post('/createUser', user.createUser); //Create Student API
app.get('/getUser',user.getUser);
//Ilan get and create
app.post('/createIlan',ilan.createilan);
app.get('/getIlan',ilan.getian);
//Location
app.get('/getlocation', location.getLocation);
};
DB.js
var mongoose = require('mongoose');
var config = require('./config');
mongoose.connect(config.dbPath);
var db = mongoose.connection;
db.on('error', function () {
console.log('error occured from db');
});
db.once('open', function dbOpen() {
console.log('successfully opened the db');
});
exports.mongoose = mongoose;
Assertion error :(function) is required - this is head of error. You should to read trace bellow this error. Hope this helps.
I need an API to android to insert data to mongodb , I'm following this , but
var song = req.body; TypeError: Cannot read property 'body' of undefined
I google few answer , which was need to install bodyParser , so I follow this to install bodyParser , but still get
var song = req.body; TypeError: Cannot read property 'body' of undefined
I'm not sure where I do wrong , please help
app code
var express = require('express'),
songs = require('./routes/route');
var app = express();
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
app.post('/songs', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
// create user in req.body
});
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
app.get('/songs',songs.addSong);
route cote
var mongoose = require('mongoose');
var mongo = require('mongodb');
var uri = "mongodb://XXXXXX:XXXXXXXX#ds061365.mongolab.com:61365/aweitest";
mongoose.connect(uri);
// we're connected!
var db = mongoose.connection.db;
var BSON = require('bson').BSONPure;
var body = require('body-parser');
db.on('error', console.error.bind(console, 'connection errrrrrrrror:'));
//db = mongoose.connection.db;
db.once('open', function() {
console.log("mongodb is connected!!");
});
exports.addSong = function(req, res) {
var song = req.body;
console.log('Adding song: ' + JSON.stringify(song));
db.collection('songs', function(err, collection) {
collection.insert(song, {safe:true}, function(err, result) {
if (err) {
res.send({'error':'An error has occurred'});
} else {
console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
}
You're not using jsonParser in your GET /songs route, only your POST /songs route. However, GET requests typically do not have request bodies. Values are typically passed in the url as query parameters in those cases, so you will probably want to instead look in req.query.
I need an API to insert data from android to mongodb , I follow this ,the code can run , have NO error , and I use POSTMAN try to post some data , it always say could not get any respone , seem to have an error connecting to 192.168.1.105:3000/songs
but I can use find all api and findByID.
This took me hours , please help , so depress :(
app.js
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
songs = require('./routes/route');
var jsonParser = bodyParser.json();
app.post('/songs', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
app.get('/songs',songs.findAll);
app.get('/findById/:id',songs.findById);
app.get('/songs',songs.addSong);
route
var mongoose = require('mongoose');
var mongo = require('mongodb');
var uri = "mongodb://XXXX:XXXX#ds061365.mongolab.com:61365/aweitest";
mongoose.connect(uri);
// we're connected!
var db = mongoose.connection.db;
var BSON = require('bson').BSONPure;
var body = require('body-parser');
db.on('error', console.error.bind(console, 'connection errrrrrrrror:'));
db.once('open', function() {
console.log("mongodb is connected!!");
});
exports.findAll = function(req, res) {
db.collection('songs',function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
exports.findById = function(req, res) {
var id = req.params.id;
console.log('Retrieving song: ' + id);
db.collection('songs', function(err, collection)
collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {
res.send(item);
});
});
};
exports.addSong = function(req, res) {
var song = req.query;
console.log('Adding song: ' + JSON.stringify(song));
db.collection('songs', function(err, collection) {
collection.insert(song, {safe:true}, function(err, result) {
{console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
};
Okay so I changed a few things in your code. I'm successfully getting the request body in the app.js file. Do have a look at the code.
route.js
var mongoose = require('mongoose');
var mongo = require('mongodb');
var uri = "mongodb://localhost:27017/test";
mongoose.connect(uri);
// we're connected!
var db = mongoose.connection.db;
var BSON = require('bson').BSONPure;
var body = require('body-parser');
db.on('error', console.error.bind(console, 'connection errrrrrrrror:'));
//db = mongoose.connection.db;
db.once('open', function() {
console.log("mongodb is connected!!");
});
exports.addSong = function(req, res) {
var song = req.body;
console.log('Adding song: ' + JSON.stringify(song));
db.collection('songs', function(err, collection) {
collection.insert(song, {safe:true}, function(err, result) {
if (err) {
res.send({'error':'An error has occurred'});
} else {
console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
}
Notice that I have changed the URI to localhost, so change it again to the one you specified.
app.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
songs = require('./routes/route');
app.post('/songs', function(req, res) {
console.log("Request.Body : " + JSON.stringify(req.body));
if (!req.body) return res.sendStatus(400);
songs.addSong(req, res);
});
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
app.get('/songs',songs.addSong);
Since your only problem was that you weren't able to get the request body. You'll be able to get it with this code.
Also since your app.get('/songs',songs.addSong); is of type GET, you'll not be able to send POST Data through it. So change it to
app.post('/songs',songs.addSong);
Hope this helps.