connecting mongodb model to apollo-server 2.0 - mongodb

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.

Related

process.env.CONNECT_DATABASE is undefined while console.log

const express = require("express");
const app = express();
const path = require("path");
require("dotenv").config({ path: path.resolve(__dirname, "./.env") });
const mongoose = require("mongoose");
console.log(process.env.DB_CONNECT);
// mongoose.connect(
// process.env.DB_CONNECT,
// { useNewUrlParse: true },
// () => console.log("connected to db!")
// );
const authRoute = require("./routes/auth");
app.use("/api/user", authRoute);
app.listen(3000, () => console.log("serve is up"));
const router = require("express").Router();
router.post("/register", (req, res) => {
res.send("Register");
});
// router.post("/login");
module.exports = router;
DB_CONNECT="mongodb+srv://<username>:<password>#fypdatabase.quhdl.mongodb.net/myFirstDatabase?retryWrites=true&w=majority"
I have installed mongoose, express, dotenv. I tried to connect user to the data base using dotenv, without dotenv it was working perfeclty fine:
moongoose.connect("url",{useNewUrlParser:true},console.log('connected');
But when I tried with dotenv and consolo logging the process.env.DB_CONNECT to see if there is value or not and it is showing undefined
const dotenv = require('dotenv');
const mongoose = require('mongoose');
dotenv.config();
// console.log(process.env.MONGO_URL);
mongoose.connect(
process.env.MONGO_URL,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log('database connected');
}
);
Maybe you specified wrong path to the .env file. Try to put .env file in the root of your application. Then just use config() without path option. .env package will by default check it for you in the root of the application.
require("dotenv").config();

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

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

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.