Unable to fetch data from mongodb using expressjs - mongodb

const express = require('express');
const bodyParser = require('body-parser');
const mongodb = require('mongodb');
const app = express();
const cors = require('cors');
app.use(bodyParser.json());
app.use(cors());
const MongoClient = mongodb.MongoClient;
const url = "mongodb://localhost:27017/recart";
app.get("/", (req, res) => {
MongoClient.connect(url,{ useNewUrlParser: true }, async (err, db) => {
if (err) throw err;
var dbo = db.db("recart");
var result = await dbo.collection("users").find()
res.json(result.data)
});
})
app.listen(3001, ()=> {
console.log('App is running on port 3001');
})
Here I am trying to fetch data from mongodb using expressjs,
but in my browser nothing is coming.
No data is coming. But in my database there are documents.
Please have a look

const url = "mongodb://localhost:27017/recart";
Do you really need to provide collection's name here?
You can try:
const mongoUrl = 'mongodb://localhost:27017/'
const MongoClient = require('mongodb').MongoClient
app.get('/', async (req, res) => {
const client = await MongoClient.connect(mongoUrl, {
useNewUrlParser: true
})
const db = client.db("database_name")
const data = await db.collection("collection_name").find().toArray()
res.json(data)
}),

Related

Why axios doesn't work with static nodejs server?

I'm having trouble getting my axios .get in production with React.
I created a nodeJS server with express to render my react page each time I want to refresh my page. That work.
But the problem is that it block my axios .get(). So, my page show normaly without the data I normaly get in dev mode.
BackEnd => server.js with sequelize module to manage my database
const express = require('express');
const app = express();
const cors = require('cors');
const path = require('path');
app.use(express.json());
app.use(cors());
const db = require('./models');
app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
const governmentCreateRouter = require('./routes/GovernmentCreate');
app.use("/governmentCreate", governmentCreateRouter);
db.sequelize.sync().then(() => {
app.listen();
});
BackEnd => GovernmentCreate.js
const express = require('express');
const router = express.Router();
const { GovernmentCreate } = require('../models');
router.get("/", async (req, res) => {
const listOfGovernments = await GovernmentCreate.findAll({
include: {all: true}
});
res.json(listOfGovernments);
});
FrontEnd => Part of code inside my GouvernmentWall.js that is called with url https://www.mon-gouvernement.fr/gouvernement-galerie
const [governmentList, setGovernmentList] = useState([]);
axios.get(`https://www.mon-gouvernement.fr/GovernmentCreate`)
.then((res) => {
console.log(res.data);
const resData = res.data;
setGovernmentList(sortResData);
}).catch((err) => {
console.log(err);
});
After multi-searching I'm thinking that the problem come from these lines in my server.js :
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
But if I remove it, when I try to refresh my page I'm getting a white page diplay Cannot GET /gouvernement-galerie.
So I'm stocking with this issu. I need your help to move forward.
Problem solve !
As #jonrsharpe mentioned, I have to switch my .get('/*' to the bottom of my routes. My server.js look like :
const express = require('express');
const app = express();
const cors = require('cors');
const path = require('path');
app.use(express.json());
app.use(cors());
const db = require('./models');
app.use(express.static(path.join(__dirname, 'build')));
//************************************************
// ROUTES
//************************************************
const governmentCreateRouter = require('./routes/GovernmentCreate');
app.use("/governmentCreate", governmentCreateRouter);
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
db.sequelize.sync().then(() => {
app.listen();
});

Unable to connect to Mongodb using moongoos

I am trying to create DB using following snippet
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const ejs = require("ejs");
const app = express();
const port = 80;
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
mongoose.connect("mongodb://localhost:27017/griData", {useNewUrlParser: true, useUnifiedTopology: true}, (err)=> {
if(err){
console.log(err);
}
});
console.log(mongoose.connection.readyState);
app.get("/", (req, res)=> {
res.render("main");
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
but when I check dbs from mongo shell, I don't see any db. What am I missing? Thanks

Unable to insert data to mongodb using express

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongodb = require('mongodb');
const app = express();
app.use(cors())
app.use(bodyParser.json());
const MongoClient = mongodb.MongoClient;
const url = "mongodb://localhost:27017/recart";
const InsertOne = () => {
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myobj = { name: "Company Inc", address: "Highway 37" };
dbo.collection("customers").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
db.close();
});
});
}
app.get("/" , (req, res) => {
InsertOne()
res.send('hello')
})
app.listen(process.env.PORT || 3000, ()=> {
console.log(`App is running on port 3000`);
})
Here i am tring to insert document into my mongodb using nodejs
In console it is showing "1 document inserted" but when i check the db nothing is there
Please have a look
The data is inserted properly. Type the following thing to check into MongoDB. In your terminal type:
mongo
use mydb
db.customers.find().pretty()

MongoDb and POSTMAN: Document isn't being added to collection

I am getting-started with mongodb.
I have set-up all the mongodb and the mongoose configuration and they work perfectly.
Here are the project files:
server.js:
const TableRow = require('./models/tableRow');
const bodyParser = require('body-parser');
const cors = require('cors')
const express = require('express');
const mongoose= require('mongoose')
const app = express();
const router = express.Router();
app.use(cors());
app.use(bodyParser.json());
mongoose.connect('mongodb://localhost/table', function(err) {
if (err) { throw err; }
console.log('Successfully connected');
});
const connection = mongoose.connection;
connection.on('error', console.error.bind(console, 'connection error:'));
connection.once('open', () => {
console.log('MongoDB database connection established successfully!');
});
app.use('/', router);
router.route('/table/add').post((req, res) => {
let tableRow = new TableRow (req.body);
tableRow.save()
.then(issue => {
res.status(200).json({'tableRow': 'Added successfully'});
})
.catch(err => {
res.status(400).send('Failed to create new record');
});
});
app.listen(5757, () => console.log(`Express server running on port 5757`));
tableRow.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
let TableRow = new Schema({
column1Data: {
type: String
},
column2Data: {
type: String
}
});
module.exports = mongoose.model('TableRow', TableRow);
When I tried testing this with POSTMAN:
I get this as you see in the response body:
{
"tableRow": "Added successfully" }
Since in server.js, I have this code:
router.route('/table/add').post((req, res) => {
let tableRow = new TableRow (req.body);
tableRow.save()
.then(issue => {
res.status(200).json({'tableRow': 'Added successfully'});
})
.catch(err => {
res.status(400).send('Failed to create new record');
});
});
I thought that should do the work. However when I type:
db.table.find()
I see that the table is empty. Any idea why?
Thank you!

Mongo-atlas connection : ReferenceError: client is not defined

when trying to connect to the mongo atlas I'm getting the error "ReferenceError: client is not defined".
Console's erro :
const db = client.db('coneccao-teste');
ReferenceError: client is not defined
See below my NodeJs code with the configuration of the Express server and mongo-atlas connection.
Have you sugestion ?
thanks!
const express = require('express');
const app = express();
const router = express.Router();
const MongoClient = require('mongodb').MongoClient;
const ObjectId = require('mongodb').ObjectId;
const port = 3000;
const mongo_uri = 'mongodb+srv://rbk:******-#cluster0-5zvdy.mongodb.net/coneccao-teste?retryWrites=true';
const db = client.db('coneccao-teste');
const collection = db.collection('inicio');
MongoClient.connect(mongo_uri, { useNewUrlParser: true })
.then(client => {
const db = client.db('coneccao-teste');
const collection = db.collection('inicio');
app.listen(port, () => console.info(`REST API running on port ${port}`));
}).catch(error => console.error(error));
// add this line before app.listen()
app.locals.collection = collection;
app.get('/', (req, res) => {
const collection = req.app.locals.collection;
collection.find({}).toArray().then(response => res.status(200).json(response)).catch(error => console.error(error));
});
app.get('/:id', (req, res) => {
const collection = req.app.locals.collection;
const id = new ObjectId(req.params.id);
collection.findOne({ _id: id }).then(response => res.status(200).json(response)).catch(error => console.error(error));
});
app.listen(port);
regarding your second problem the collection is just not defined.
when you declare:
app.locals.collection = collection;
your mongo connection has probably not connected yet meaning that collection is undefined at that point
insert this declaration after the connection is established and before you start listening with ur app:
MongoClient.connect(mongo_uri, { useNewUrlParser: true })
.then(client => {
const db = client.db('coneccao-teste');
const collection = db.collection('inicio');
app.locals.collection = collection;
app.listen(port, () => console.info(`REST API running on port ${port}`));
}).catch(error => console.error(error));
now the collection is guaranteed to be defined the way you expect it to be when starting your app.