Mongo-atlas connection : ReferenceError: client is not defined - mongodb

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.

Related

How to connect to Mongo db server remotely through its default ports?

I'm trying to connect to a mongo db server remotely through the default port to view the db contents. Suggest me how to do that remotely , it could also be either through python or node.js.
To connect remotely to a mongodb server, then all you will need is :
*. database URI
Which comprises of database name and authentication if needed
Sample code for connecting to remote mongodb shared atlas cluster is like this:
const express = require('express')
const app = express()
var cors = require('cors')
const { MongoClient } = require('mongodb')
const uri = 'mongodb+srv://xxx-sampledb:xxx-mongodb-
sampledb#sandbox.xxxx.mongodb.net/ellasShop?authSource=admin';
//middleware
app.use(express.json())
app.use(cors())
//initialize db connectivity options
const options = {
useUnifiedTopology: true,
useNewUrlParser: true,
}
app.get('/api/products', async (req, res) => {
const client = new MongoClient(uri, options);
try {
await client.connect();
const database = client.db('ellasShop')
const collection = database.collection('productData')
const products = await collection.findOne();
return res.json(products);
} catch (err) {
console.log(err)
} finally{
await client.close()
}
})
app.listen(5000, () => {
console.log('Server is running')
})

How to get all the collections of MongoDB?

I want to get access to all the collections of my MongoDB database.
But I am unable to do so.
I am using mongoose.connection.db.getCollection(collection_name) just above the listen part of code but console is saying
mongoose.connection.db.getCollection is not a function.
Here is my code
import express from "express";
import mongoose from "mongoose";
import Messages from "./messages.js";
import dynamicModel from "./messagesRoom.js";
import cors from "cors";
// app configuration
const app = express();
const port = process.env.PORT || 9000;
//middleware
app.use(express.json());
app.use(cors());
// DB Configuration
const url = "mongodb+srv://username:password#cluster0.zp9dc.mongodb.net/Whatsapp_MERN";
mongoose.connect(url, {useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true})
.then(()=> console.log('mongoDB is connected'))
.then(err => console.log(err));
const db = mongoose.connection;
db.once('open', () => {
console.log("DB is connected");
const msgCollection = db.collection('messagecontents');
const changeStream = msgCollection.watch();
changeStream.on('change', (change) => {
console.log(change);
if(change.operationType === 'insert'){
const msgDetails = change.fullDocument;
pusher.trigger('messages', 'inserted',
{
name: msgDetails.name,
message: msgDetails.message,
timestamp: msgDetails.timestamp,
received: msgDetails.received,
})
}
else{
console.log('Error triggering pusher');
}
})
})
// API routes
app.get("/", (req, res) => {
res.status(200).send("Hello World");
})
app.get("/messages/sync", async (req, res) => {
await Messages.find( (err, data) => {
if(err){
console.log(err);
res.status(500).send(err);
}else{
res.status(200).send(data);
}
})
})
app.post("/changeChat", (req, res) => {
const collection_name = req.body.chatName;
let collection = mongoose.connection.db.getCollection("collection_name");
console.log(collection);
})
// listening part
app.listen(port, () => console.log(`listening on port number ${port}`));
please suggest me a way using which I can get access to collections of database according to the name I am using.
mongoose.connection.on('open', function (ref) {
mongoose.connection.db.listCollections().toArray(function(err, names){
console.log(names)
})
})
Try this code block below "mongoose.connect()", the 'listCollections()' function will return the list of all the collection in the respective database and 'toArray()' function will convert that list into array, then we simply log the array.

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()

Unable to fetch data from mongodb using expressjs

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)
}),

connecting mongodb model to apollo-server 2.0

I am following a tutorial which uses mongo database with graphql, currently the tutor uses apollo-server v1 but I am using apollo-server v2, the problem I'm having is where do i make the connection of my models to graphql,
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");
require("dotenv").config({ path: "variables.env" });
const Recipe = require("./models/Recipe");
const User = require("./models/User");
// Bring in GraphQL-Express middleware
const { graphiqlExpress, graphqlExpress } = require("apollo-server-express");
const { makeExecutableSchema } = require("graphql-tools");
const { typeDefs } = require("./schema");
const { resolvers } = require("./resolvers");
// Create schema
const schema = makeExecutableSchema({
typeDefs,
resolvers
});
// Connects to database
mongoose
.connect(process.env.MONGO_URI)
.then(() => console.log("DB connected"))
.catch(err => console.error(err));
// Initializes application
const app = express();
const corsOptions = {
origin: "http://localhost:3000",
credentials: true
};
app.use(cors(corsOptions));
// Create GraphiQL application
app.use("/graphiql", graphiqlExpress({ endpointURL: "/graphql" }));
// Connect schemas with GraphQL
app.use(
"/graphql",
bodyParser.json(),
graphqlExpress({
schema,
context: {
Recipe,
User
}
})
);
const PORT = process.env.PORT || 4444;
app.listen(PORT, () => {
console.log(`Server listening on PORT ${PORT}`);
});
so in apollo-server v1 you pass in your mongo schema (models) in graphqlExpress
Connect schemas with GraphQL
app.use(
"/graphql",
bodyParser.json(),
graphqlExpress({
schema,
context: {
Recipe,
User
}
})
);
but in v2 you no longer use graphqlExpress function,
https://www.apollographql.com/docs/apollo-server/v2/migration-two-dot.html
so how/where do i pass in my database models to?
currently I have this
const express = require ('express')
const mongoose = require ('mongoose')
const { ApolloServer } = require('apollo-server-express');
require('dotenv').config({path: 'variables.env'})
// mongo schemas/models
const Recipe = require('./models/Recipe')
const User = require('./models/User')
//Graphql schema
const {typeDefs} = require('./schema')
const {resolvers} = require('./resolvers')
// connects to database
mongoose.connect(process.env.MONGO_URI, {useNewUrlParser: true} )
.then(()=> console.log('DB connected'))
.catch(error => console.log(error))
const PORT = process.env.PORT || 4444;
const server = new ApolloServer({ typeDefs, resolvers });
const app = express();
server.applyMiddleware({ app });
app.listen({ port: PORT }, () =>
console.log(`🚀 Server ready at http://localhost:${PORT}${server.graphqlPath}`)
)
If you want to be exactly like you were before, you need to add the context function onto your ApolloServer init:
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => ({
Recipe,
User
})
});
This example works perfect with PG, if you are using Mongo, just replace pg calls with mongoose and you should be good to go.