Unable to connect to mongoDB client using mongoose - node.js

I am a beginner in mongoose and mongo DB. When I am trying to connect to mongoDB using mongoose , running the app.js file with the help of node app.js the process is struck.
I am not getting any output. When I am checking the database then also the database is not created.
Can anyone please tell me where I am going wrong?
This is my code:
const mongoose = require('mongoose');
var conn = mongoose.connect('mongodb://localhost:27017/my_database', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const peopleSchema = new mongoose.Schema ({
name: String,
age: Number
});
const People = mongoose.model("People",peopleSchema);
const people = new People({
name : "Umang",
age: 25
})
people.save();

Try the following command in your command prompt
npm install express
Then add the following code snippet.
const mongoose = require('mongoose');
const express = require('express')
const app = express()
var conn = mongoose.connect('mongodb://localhost:27017/my_database', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const peopleSchema = new mongoose.Schema({
name: String,
age: Number
});
const People = mongoose.model("People", peopleSchema);
const people = new People({
name: "Umang",
age: 25
})
people.save();
app.listen(3000, function () {
console.log('Node server listening on port 3000');
})
I have tested it and it is working.
Make sure MongoDb is connected

Related

Make sure the first parameter to `mongoose.connect()` is a string

I'm trying to connect MongoDB Atlas to my application and ran into this error when trying to run the mongoose.connect(), which is located in db.js (last code in the question). process.env.MONGO_URI seems to be interpreted as undefined and not string, giving the following error: "MongooseError: The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string."
this is the my config.env, in which I copy pasted the MONGO_URI from the Atlas.
MONGO_URI = mongodb+srv://kpae:XXXX#practice.xujsvaf.mongodb.net/?retryWrites=true&w=majority
this is app.js, where I believe I set up the basics to run the program.
const express = require('express')
const dotenv = require('dotenv')
const connectDB = require('./config/db')
dotenv.config({ path: '.config/config.env' })
connectDB()
const app = express()
const PORT = process.env.PORT || 5000
app.listen(
PORT,
console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`)
)
this is db.js
const mongoose = require('mongoose')
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
})
console.log(`MongoDB Connected: ${conn.connection.host}`)
} catch (err) {
//console.log('this is an error')
console.error(err)
process.exit(1)
}
}
module.exports = connectDB
I'm having trouble pinpointing where the bug lies in my code because it seems like my files are in the root folder and MONGO_URI looks like a string. Any help is appreciated.
Can you please try once like this in your env file?
MONGO_URI='mongodb+srv://kpae:XXXX#practice.xujsvaf.mongodb.net/?retryWrites=true&w=majority'

Localhost:3000 not opening from node.js app

I've set up a tiny little app which is run using Express, Nodemon and Mongoose.
A few hours ago, it worked fine - and I don't think I've changed any of the code then. If I have, it must have been accidentally.
But whenever I try to access my localhost for this particular app, it doesn't load. It just sits in this state of loading. No errors appear, the console is clear and it states 'Running on Port 3000'.
If I try other apps, they work fine on localhost, so it must be the code - but I don't even know where to start considering there's no error messages.
Here's my code:
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
var encrypt = require('mongoose-encryption');
require("dotenv").config();
const app = express();
mongoose.connect(process.env.MONGO_URI, {useNewUrlParser: true, useUnifiedTopology: true});
const SubmitDebtSchema = new Schema ({
balance: [{
balanceDate: Date,
newBalance: Number
}],
monthly: Number,
date: String,
autoBalance: String
});
const encKey = process.env.ENCKEY;
const sigKey = process.env.SIGKEY;
SubmitDebtSchema.plugin(encrypt, { encryptionKey: encKey, signingKey: sigKey, excludeFromEncryption: ['autoBalance'] });
const SubmitDebt = mongoose.model('submitdebt', SubmitDebtSchema);
app.get("/", async (req, res) => {
const debts = await SubmitDebt.find({ autoBalance: true });
debts.map(debt => {
console.log(debt.id);
const debtDate = parseInt(debt.date);
const finalDate = new Date(new Date().setDate(debtDate));
console.log(finalDate);
const todaysDate = new Date();
console.log(todaysDate);
const debtBalance = debt.balance[debt.balance.length - 1].newBalance;
console.log(debtBalance);
const debtRepayment = debt.monthly;
console.log(debtRepayment);
const updatedBalance = { balanceDate: new Date(), newBalance: debtBalance - debtRepayment };
console.log(updatedBalance);
if (todaysDate < finalDate) {
console.log("Balance shouldn't change.");
}
if (todaysDate >= finalDate) {
console.log("Balance should change");
SubmitDebt.findById(debt._id, (err, submitdebt) => {
if (!submitdebt) {
console.log("Unable to find entry to edit.");
}
else {
submitdebt.balance.push(updatedBalance);
submitdebt.save().then(submitdebt => {
console.log("Debt successfully updated.");
})
.catch(err => {
console.log("Debt unsuccessfully updated.");
});
}
});
}
res.send(debts);
});
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Lemio is running on port ${ PORT }`);
});
Can anyone spot any reason why my localhost isn't working for this app? Feel like I'm missing something obvious!
Some thoughts:
kill the process and start it over;
check if your port is busy with some other app;
check is mongod is running.
Links:
How To Use ps, kill, and nice to Manage Processes in Linux
How to check if port is in use on Linux or Unix
Manage mongod Processes

Connecting a node api to a cosmosdb

I'm am trying to connect my react app with a node api to my cosmos db. I'm able to get the server running but when I send a post or get request I don't get a response. I've updated the firewall to allow my ip and I've read just about every article I can find on connecting to cosmos, but none of the resources have helped.
Here is the connection code
const mongoose = require('mongoose');
const env = require('./env/environment');
mongoose.set('useNewUrlParser', true);
mongoose.set('useUnifiedTopology', true);
mongoose.Promise = global.Promise;
const mongoUri = `mongodb://${env.dbName}:${env.key}#${env.dbName}.mongo.cosmos.azure.com:${env.cosmosPort}/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=#${env.dbName}#`;
function connect() {
return mongoose.connect(mongoUri, { auth: { user: env.dbName, password: env.key }});
}
module.exports = {
connect,
mongoose
};
and then the env file looks like this
const cosmosPort = 1234; // replace with your port
const dbName = 'your-cosmos-db-name-goes-here';
const key = 'your-key-goes-here';
module.exports = {
cosmosPort,
dbName,
key
};
The env file has the actual information this is just an example.
Are you sure .env file can use const to define params? I'm not sure that. But I follow the offical document, I can connnect cosmosdb successfully.
It is recommended to refer to my screenshot, create a .env file, and replace your parameters to try.
var mongoose = require('mongoose');
var env = require('dotenv').config();
mongoose.connect("mongodb://"+process.env.COSMOSDB_HOST+":"+process.env.COSMOSDB_PORT+"/"+process.env.COSMOSDB_DBNAME+"?ssl=true&replicaSet=globaldb", {
auth: {
user: process.env.COSMODDB_USER,
password: process.env.COSMOSDB_PASSWORD
},
useNewUrlParser: true,
useUnifiedTopology: true,
retryWrites: false
})
.then(() => console.log('Connection to CosmosDB successful'))
.catch((err) => console.error(err));
I think your mongoUri need to be in this format mongodb://${env.dbName}:${env.key}#${env.dbName}.mongo.cosmos.azure.com:${env.cosmosPort}/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=#${env.dbName}#
Took some digging for me, and the documentation isn't great.

Unable to connect to MongoDB cloud by following code. I need to know whats wrong with this code?

I am unable to connect to cloud mongodb with the following code. Can anyone please tell me whats wrong with this code?
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
//body parser middleware
app.use(bodyParser.json());
//db config
const db = require('./config/keys').mongoURI;
//Connect to mongo
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => console.log("MongoDB connected"))
.catch(err => console.log(err));
const port = process.env.PORT || 5000;
app.listen(port, () => console.log('server started on port ${port}'));
There are multiple steps you should follow to be able to connect Mongo DB so first make sure that you created an account plus connecting to a cluster, while creating it you'll be provided with enough info to create a cluster take your time and read.
after doing that the code is very simple:
const mongoose = require("mongoose");
mongoose.connect(
"mongodb+srv://[ACCOUNT NAME]:[PASSWORD]#cluster0-sxlgp.gcp.mongodb.net/test?retryWrites=true&w=majority", { useNewUrlParser: true }
);
replace ACCOUNTNAME and PASSWORD with info you provided when you created your MongoDB account
This can be found in their documentation try taking your time reading the documentation.
I believe your code looks good the error you are getting TransientTransactionError is temporary please use events to handle your connection result
mongoose
.connect(db, { useNewUrlParser: true })
mongooose.connection.once('open', () => {
console.log('db connection success');
});
mongooose.connection.on('err', (err) => {
console.log('db connection failed');
});

JSON String appears to be blank in node js

I am trying to create web services using node js,express and mongoose.
this is my app.js file
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
GetData = require('./models/women');
mongoose.connect('mongodb://localhost/shopping');
var db = mongoose.connection;
app.get('/api/getCategories',function(req,res){
GetData.getCategory(function(err,getCategory){
if (err) {
throw err;
}
res.json(getCategory);
});
});
app.get('/',function(req,res){
res.send('Hi i am Madhura. Nice to Meet u. lets start creating web services');
});
app.listen(3000);
console.log('connected to Port 3000');
this is my women.js file
var mongoose = require('mongoose');
var categorySchema = mongoose.Schema({
name:{
type: String,
required: true
}
});
var Category = module.exports = mongoose.model('',categorySchema);
module.exports.getCategory = function(callback,limit){
Category.find(callback).limit(limit);
}
I am unable to understand this line
var Category = module.exports = mongoose.model('',categorySchema);
I have left this ' ' blank because I wanted to know what parameter is passed here
I watched a video about this, and could not find a conclusion. however, I simply followed the video and run the code. but my output is coming to be a null JSONArray "[]". Please tell me what am i doing wrong.
var mongoose = require('mongoose');
var categorySchema = mongoose.Schema({
name:{
type: String,
required: true
}
});
var Category = mongoose.model('Category',categorySchema);
module.exports.getCategory = function(callback,limit){
Category.find(callback).limit(limit);
}
The part you have made '' contains the mongoose model name that you can use to refer the respective MongoDB collection. you can imagine a model name as replacement of db.collectionname for MongoDB. I have updated the codebase

Resources