Unable to connect to Mongodb using moongoos - mongodb

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

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

I am trying to store my node rest api data to mongodb atlas. But getting insertion errors

I am trying to register the user to mongodb atlas for registration and login but i am geting an error 404.
here is full link to mycode
https://github.com/badrinathareddyr/falcon.git
server.js file
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const authRoute = require('../backend/routes/auth')
//connect to database
dotenv.config({ path: __dirname + '/.env' });
mongoose.connect(
process.env[DB_CONNECT], { useNewUrlParser: true }, () =>
console.log('connected to db!')
);
//Middleware
app.use(express.json());
//middlewareroutes
app.use('/register', authRoute);
app.listen(3000, () => console.log('server up and running'));
auth.js file
var express = require('express');
const router = express.Router();
const User = require('../models/User');
const bcrypt = require('bcryptjs');
router.post('/register', function (req, res) {
if (!req.body.email || !req.body.password) {
res.json({ success: false, msg: 'Please pass email and password.' });
} else {
var newUser = new User({
email: req.body.email,
password: req.body.password
});
// save the user
newUser.save(function (err) {
if (err) {
return res.json({ success: false, msg: 'Email already exists.' });
}
res.json({ success: true, msg: 'Successful created new user.' });
});
}
});
module.exports = router;
It's because of process.env.DB_CONNECT in your code is undefined. Change line 5 of your src/backend/server.js file like below:
const dotenv = require('dotenv').config({ path: __dirname + '/.env' });
then comment dotenv.config()
and copy .env to src/backend/.
Or change line 10 or the file like this:
dotenv.config({ path: __dirname + '/.env' });
You have const User = require('../models/User'); two time in backend/routes/auth.js. Comment line 9. It will give you error.
I fixed it and created pull request in github. Merge it.

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.