How can I display my mongoDB query as json using express? - node.js

When I use nodemon to start my express server, it constantly loads in the browser and will not load any of my application.
This is the code in my dbconn.js and app.js files. I cannot figure out how to pull and display my query in order to verify my connection to the db. I am a total beginner in using mongoDB and express. Please help.
It is not throwing any exceptions, so I can't figure out what I am doing wrong.
const mongoose = require('mongoose')
const MongoClient = require('mongodb').MongoClient;
const express = require('express');
const router = express.Router();
const uri ='mongodb+srv://<username>:<password>#wager0-mhodf.mongodb.net/test?retryWrites=true&w=majority';
const client = new MongoClient(uri, { useUnifiedTopology: true, useNewUrlParser: true });
client.connect(err => {
console.log("Connected successfully to server");
router.get('/', function(req, res, next) {
const collection = client.db("wager0").collection("gameTypes");
// Get first two documents that match the query
collection.find({a:1}).limit(2).toArray(function(err, docs) {
res.json({length: docs.length, records: docs});
});
client.close();
});
});
module.exports = router;
var dbconnRouter = require('./services/dbconn');
app.use('/dbconn', dbconnRouter);

Related

How to redirect page after using the DELETE method in express?

I'm a newbie in Nodejs and I'm coding a to-do app as a practical exercise. I'm having a problem that I cannot return to my index page "/" after using the DELETE method in Express. I use the deleteMany() of Mongoose to delete my docs, however after deleted all of those docs I couldn't return to the "/" page, the system threw an error in the console:
DELETE http://localhost:3000/ 404 (Not Found)
although using res.redirect("/") is fine with POST method. I've found a guy with the same problem as mine on Stack Overflow, but his solutions are not working in my app. Another solution of him is using pure Javascript to redirect from the client, however I want to do this job in the severside.
My files:
routes.js
module.exports = function(app) {
var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true, useUnifiedTopology: true});
var db = require("./db");
app.get("/", function(req,res,next) {
db.task.find()
.then(tasks => {
res.render("index", {tasks: tasks})
});
})
}
controller.js
module.exports = function(app) {
const routes = require("./routes.js");
const apiRoutes = require("./api.js");
app.use(function(req,res,next) {
console.log(`GET ${req.url}`);
next();
})
app.use("/api", apiRoutes);
routes(app);
}
api.js
var express = require("express");
var bodyParser = require("body-parser");
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var router = express.Router();
const mongoose = require("mongoose");
mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true, useUnifiedTopology: true});
var db = require("./db");
router.post("/post", urlencodedParser, function(req,res) {
new db.task({"name": req.body.item, "status": "incompleted"})
.save(err => {
if (err) throw err;
console.log(req.body.item);
});
res.redirect("/");
}).delete("/delete/:item", function(req,res) {
var result = [];
var item = req.params.item;
//Config the url task to its original name
var delTask = item.replace(/\-/g," ").replace(/;/g,"-");
//Logging out the deleted task
db.task.find({"name": delTask}).then((foundTasks) => {
foundTasks.forEach(function(tasks){
var removedDoc = {"name": tasks.name, "Object_Id": tasks._id};
result.push(removedDoc);
})
})
db.task.deleteMany({"name": delTask}, (err) => {
if (err) throw err;
console.log("Removed items: ", result);
})
res.redirect("/");
})
module.exports = router;
You don't have to worry about the db.js file, because it just help me to create mongoose schema and completely do nothing with http or express. And finally the controller.js will be required in the app.js.

Cannot read property 'find' of undefined when requesting data from db

I am very new to back end development, so I am watching a tutorial. In the tutorial, mlabs is used, but Mongo Atlas seems to work differently. I am trying to display my posts using a get request, but am getting this error:
TypeError: Cannot read property 'find' of undefined
at C:\Users\reaga\Desktop\Projects\fullstack-crud\server\routes\api\posts.js:10:26
posts.js
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const router = express.Router();
// Get post
router.get('/', async (req, res) => {
const posts = await loadPostsCollection();
res.send(await posts.find({}).toArray());
});
// Add post
// Delete post
async function loadPostsCollection() {
// Adding connection string to var
const uri = 'mongodb+srv://nova:nova123#cluster0.deckb.mongodb.net/Cluster0?retryWrites=true&w=majority';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
await client.connect(err => {
client.db('Project 0').collection('posts');
});
}
module.exports = router;

mongoose connects only to localhost

I always get "Listening at localhost" but the URL I put is from Mongo Atlas. And when I print the environment variable to the console I get it correctly. mongoose automatically ignores any url other than localhost.
I have tried to restart nodemon muiltiple times.
mongoose
.connect(process.env.DATABASE_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log(process.env.DATABASE_URL); //prints the correct url but mongoose connects to localhost
console.log("mongo connected");
// logEntry.collection.drop();
})
.catch((error) => console.log(error.message));
validate the connection using the below mentioned code snippet.
const express = require('express');
const app = express();
const socketio = require('socket.io');
const mongoose = require('mongoose');
const expressServer = app.listen(3001);
const io = socketio(expressServer);
mongoose.connect('mongodb+srv://<UserName>:<Password>#democluster0.abcde.mongodb.net?retryWrites=true&w=majority');
mongoose.connection.on('open', function (ref) {
console.log('Connected to mongo server.');
mongoose.connection.db.listCollections().toArray(function (err, names) {
console.log(names);
});
})
Refer the below link to gain the URL for the same..
https://docs.atlas.mongodb.com/tutorial/connect-to-your-cluster/

TypeError: Cannot read property 'db' of null

I am having issue connecting to mongodb atlas, getting the error below
let express = require('express')
let mongodb = require('mongodb')
let app = express()
let db
let connectionString = 'mongodb+srv://olumide:xxxxxxxx#cluster0-edskm.mongodb.net/todoApp?retryWrites=true&w=majority'
mongodb.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client){
db = client.db()
app.listen(3000)
})
app.use(express.urlencoded({extended: false}))
app.post('/create-item', function(req,res){
db.collection('item').insertOne({text: req.body.item}, function(){
res.send("thanks for submitting the form")
})
})
Error message
This is because the mongo.connect function is asynchronous. You will need to include the app.post function inside of the mongo.connect callback.
Something kind of like this should work:
let express = require('express')
let mongodb = require('mongodb')
let app = express()
app.use(express.urlencoded({extended: false}))
let connectionString = 'mongodb+srv://olumide:xxxxxxxx#cluster0-edskm.mongodb.net/todoApp?retryWrites=true&w=majority'
mongodb.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client){
const db = client.db()
app.post('/create-item', function(req,res){
db.collection('item').insertOne({text: req.body.item}, function(){
res.send("thanks for submitting the form")
})
})
app.listen(3000)
})
I figured out, in newer versions of MongoDB (3 and higher) they have essentially changed the way of connecting node server to the database. To establish a reusable connection (So that we can access the connected database from any other file), I created an async function in my db.js file where the connection is established and then exported it. In the end of the file, I have called the function. The code is as follows:
const {MongoClient} = require('mongodb')
const client = new MongoClient('mongodb+srv://todoAppUser:<password>#cluster0.6lvjr.mongodb.net/myDatabase?retryWrites=true&w=majority')
async function start(){
await client.connect()
console.log("Connected")
module.exports = client.db()
const app = require('./app')
app.listen(3000)
}
start()
and while calling it from another file:
const productCollection = require('./db').collection("product");
This code gives me no error and works perfectly fine. With the help of the above code, one can use this conveniently while following the MVC (Model-View-Controller) framework.
use mongoose connection as a different javascript file and import it to express script file
database.js
let mongoose = require('mongoose');
const server = '127.0.0.1:27017'; // REPLACE WITH YOUR DB SERVER
const database = 'test'; // REPLACE WITH YOUR DB NAME
class Database {
constructor() {
this._connect()
}
_connect() {
mongoose.connect(`mongodb://${server}/${database}`,{ useUnifiedTopology: true ,useNewUrlParser: true, useFindAndModify: false})
.then(() => {
console.log('Database connection successful')
})
.catch(err => {
console.error('Database connection error')
})
}
}
module.exports = new Database()
strong text

Mongo models not responding

I'm working on a new app and trying to get mongo set up locally for storage. My api endpoints are getting hit but as soon as I try to actually call a db operation - find or save - it doesn't respond.
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Person = require('./data/person');
var dbConfig = require('./config');
//database: 'mongodb://localhost:27017/persondb'
var db = mongoose.createConnection(dbConfig.database);
db.on('error', function() {
console.info('Error: Could not connect to MongoDB. Did you forget to run `mongod`?');
});
if (~process.argv.indexOf('mode_dev')) {
global.mode_dev = true;
console.log('Server started in dev mode.');
}
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', router);
router.route('/persons')
.post(function(req, res) {
debugger;
var person = new Person(); // create a new instance of the Person model
person.name = req.body.name;
person.save(function(err) {
debugger;
if (err)
res.send(err);
res.json({ message: 'Person created!' });
});
})
.get(function(req, res) {
Person.find(function(err, persons) {
debugger;
if (err)
res.send(err);
res.json(persons);
});
});
Here's the schema:
data/item.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var personSchema = new Schema({
name: String,
});
module.exports = mongoose.model('Person', personSchema);
I am running mongod before getting my webserver started. As soon as I get to the .save or .find calls, no error is thrown but the callbacks are never hit.
I would connect like this:
mongoose.connect("mongodb://localhost/persondb");
var db = mongoose.connection;
maybe this will help it explains problems using mongoose.createConnection(
if you use createConnection, you need to always reference that connection variable if you include a registered model, otherwise if you use mongoose to load the model, it will never actually talk to your database.
The other solution is to simply use mongoose.connect instead of
mongoose.createConnection. Then you can just use
mongoose.model(‘MyModel’) to load the requested model without needing
to carry around that db connection variable.

Resources