when trying to connect to mongo db from the project directory i get this
/Users/tadeothompson/Documents/design work/stressful/site/node_modules/connect-mongo/lib/connect-mongo.js:133
throw err;
^
MongoError: cannot connect to server
at Collection.listIndexes (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/collection.js:1712:11)
at indexInformation (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/db.js:1531:25)
at Db.indexInformation (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/db.js:1498:44)
at ensureIndex (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/db.js:1003:8)
at Db.ensureIndex (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/db.js:982:44)
at ensureIndex (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/collection.js:1772:13)
at Collection.ensureIndex (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/collection.js:1760:44)
at connectionReady (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/connect-mongo/lib/connect-mongo.js:141:27)
at Db.collection (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/db.js:425:20)
at initWithNativeDb (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/connect-mongo/lib/connect-mongo.js:207:20)
at process._tickCallback (node.js:355:11)
at Function.Module.runMain (module.js:503:11)
at startup (node.js:129:16)
at node.js:814:3
managed to connect using a simple app (code below)
*
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(!err) {
console.log("We are connected");
}
});
*
the main node file of the app in question code is below:
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var mongoStore = require('connect-mongo')({session: expressSession});
var mongoose = require('mongoose');
require('./models/users_model.js');
var conn = mongoose.connect('mongodb://localhost:27017/stressfullproject');
var app = express();
app.engine('html', require('ejs')._express);
app.set('views', './site' + '/views');
app.set('view engine', 'html');
app.use(bodyParser());
app.use(cookieParser());
app.use(expressSession({
secret: 'stress',
cookie: {maxAge: 60*60*1000},
store: new mongoStore({
db: mongoose.connection.db,
collection: 'sessions'
})
}));
require('./routes/routes')(app);
app.listen(80);
*
my defined schema
*var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var UserSchema = new Schema({
username: { type: String, unique: true },
email: String,
hashed_password: String
})
mongoose.model('User', UserSchema)*
because i can connect with the other app, im thinking its an issue with one of my modules? ive searched all over.
thanks in advance
My best guess is that you are using two modules namely MongoClient and mongoose both are trying to connect to port 27017. Now in this race only one will win and will lock that port. If you try and bind to that port it will give you an error, similar to the one you are getting above. My suggestion, don't use MongoClient. use only mongoose. There is a lot of help available for mongoose and many video tutorials on youtube use it.
If that doesn't help let me know.
Let's prep you up with some code shall we. I don't use MongoClient now, but when I used to I wrote this code, see of it works. If it doesn't please paste the stacktrace.
var MongoClient=require('mongodb').MongoClient,
server=require('mongodb').Server;
var mongoclient=new MongoClient(new server('localhost',27017));
mongoclient.connect('mongodb://localhost:27017/course',function(err,db)
{
if(err) throw err;
//var db=mongoclient.db('course');
var query={'grade':100};
db.collection('grades').findOne(query,function(err,doc)
{
if(err) throw err;
console.dir(doc);
db.close();
});
});
i found the answer in another stack overflow post here
the problem was that the session (or something else outside of mongoose) was trying to connect to the database BEFORE mongoose established a connection.
Either one of two issues - either you are calling an undefined schema (mongoose) or you have a function requiring next but next is undefined. I've run into this problem many times and it's documented lack of error handling with mongoose. You need to define some error handling early in your app.js file.
Mongodb version v4.2.6 ---
Node.js version: v14.2.0
first, make sure you are running mongodb local server, check for exsiting db by bellow command:
show dbs
output:
Now I want to connect with database tours-test
first install mongooes by command
npm i mongoose
Now in you connection.js
const mongoose = require('mongoose');
const conStr = 'mongodb://localhost:27017/tours-test';
mongoose
.connect(conStr, {
usedNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
})
.then((con) => console.log('DB connection successful'));
// remember mongoose.connect() return Promise
Related
I'm building a cafe website with NodeJS, Express, and Mongo. I'm attempting to create a new cafe in one of my routes with a get request using a model I created. However, I keep getting an TypeError in my terminal stating that Cafe is not a constructor. I don't understand because I have defined the Schema in a separate file and I've included it in my app.js (routes file). Any feedback about this error is appreciated. I've included a few photos along with the code. Thank you in advance!
const path = require('path')
const mongoose = require('mongoose');
const Cafe = require("./models/cafe");
mongoose.connect('mongodb://localhost:27017/cafe-hopping', {
useNewURLParser: true,
useUnifiedTopology: true
})
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
console.log("Database connected");
});
const app = express()
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))
app.get('/createcafe', async(req, res) => {
const cafes = new Cafe ({ name: 'Cueva Matera', description: "A cave like theme cafe"});
await cafes.save();
res.send(cafes)
})
*The following is the Schema (the file name is cafe.js)*
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CafeSchema = new Schema({
name: String,
price: String,
description: String,
location: String
});
module.export = mongoose.model('Cafe', CafeSchema);
[![app.js file. This is where I am keeping all of my routes][1]][1]
[![cafe.js file. This is where I create a new Schema for the database][2]][2]
[![This is the server error message I'm getting in my terminal every time I send the /createcafe get request][3]][3]
[1]: https://i.stack.imgur.com/mgTYg.png
[2]: https://i.stack.imgur.com/p9Ibx.png
[3]: https://i.stack.imgur.com/hFzzJ.png
The issue appears to be that you should be using
module.exports = mongoose.model('Cafe', CafeSchema);
Instead of module.export
Because of the misnamed property (export vs exports) the schema is not getting exported correctly, and Cafe is not a constructor.
This is my connection file
const connectDB = async () =>{
const conn = await new mongoose("mongodb+srv://nikunj:gadia7420#cluster0.94xph.mongodb.net/myFirstDatabase?retryWrites=true&w=majority",
{
usenewurlparser:true,
usecreateindex:true,
usefindmodify:true,
useunifiedtropology:true,
urlencoded:true
})
}
module.exports = connectDB;
this is my models file
const userSchema = new mongoose.Schema({
username:{
type:String,
required:true
},
avatar:{
type:String,
},
email:{
type:String,
required:true
},
password:{
type : String,
required:true
}
});
module.exports = mongoose.model('user',userSchema);
this file will insert or take information from database for registeration
const express = require('express');
const router = express.Router();
const User = require('../models/user');
const bcrypt= require('bcrypt');
router.post('/register',async(req,res,next)=>{
const {username,email,password}=req.body;
try{
let user_exist = await User.findOne({email:email});
if(user_exist){
success="false";
msg="user already exist";
} else {
//importing data to models
let user = new User();
user.username = username;
user.email = email ;
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password,salt),
user.avatar = "https://gravatar.com/avatar/?s=200&d=retro"
await user.save();
res.json({
sucess:true,
user:user,
msg:"user registered"
})
}
}
catch(err){
console.log(err);
}
});
module.exports = router;
this is my main file (server.js )
const express = require('express');
const morgan = require('morgan');
const colors = require('colors');
const dotenv = require('dotenv');
const mongoose = require('mongoose');
const connectDB = require('./config/db');
//creating main platform
connectDB;
console.log(mongoose.connection.readyState);
const app = express();
app.use(morgan('dev'));
dotenv.config({
path:'./config/config.env'
})
app.use(express.json({}))
app.use(express.json({
extended:true
}))
//creating server
app.use('/api/todo/auth',require('./routes/user'));
const Port = process.env.port;
app.listen(Port,
console.log(`listening on port :${Port}` .red.underline.bold));
//creating req,res platform
but after running this it shows error while giving post request
MongooseError: Operation `users.findOne()` buffering timed out after 10000ms
at Timeout.<anonymous> (D:\nikunj\Programming\todoapp\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:185:20)
at listOnTimeout (node:internal/timers:556:17)
at processTimers (node:internal/timers:499:7)
pls find a solution for this. thanks .sorry if it is a silly or wrong question because I am new to this nodejs
Connect to your database 1st and after that start your server.
You're trying to query the database without connecting to your database.
https://mongoosejs.com/docs/connections.html#buffering
Mongoose lets you start using your models immediately, without waiting for mongoose to establish a connection to MongoDB.
That's because mongoose buffers model function calls internally. This buffering is convenient, but also a common source of confusion. Mongoose will not throw any errors by default if you use a model without connecting.
connectDB()
.then(() -> {
app.listen(Port, console.log(`listening on port :${Port}` .red.underline.bold));
}).catch((e) => {
console.log(e);
})
You're not calling the function connectDB
Turn on your Mongo Server and connect to your database before you attempt to write to it.
In my case I am using a monorepo, one package initiates the server and another contains the mongoose models.
One of the packages had a different mongoose version on it's package.json's dependencies.
The problem was fixed after making sure both packages had the same version of mongoose and then running yarn at the root of the monorepo to relink dependencies properly.
For anyone wondering, I'm able to use mongoose on two different packages in a monorepo since mongoose is basically a singleton class, meaning that it will usually try to use a pre-existing instance of mongoose wherever it is mentioned without initialization.
Having two versions of mongoose breaks this singleton functionality since (as far as Node is concerned) the instance on the server was created using a different mongoose package than the one on my models package.
TL;DR Make sure any packages in your monorepo depending on mongoose have the same version of mongoose in their respective package.json files.
This question has already been answered, however when I encountered with the same problem, the cause was very different. For some reason I put Mongodb connection URI inside quotes in config vars. Never do that. When I removed the quotes, everything worked just fine.
I faced this problem at mongoose v "^6.3.4" and when I removed my IP from network access on sidebar on mongodb and added it again it worked
I faced this problem at mongoose v "^6.3.4" and when I removed my IP
from network access on sidebar on mongodb and added it again it worked
This worked for me too. I removed my ip and selected "ALLOW ACCESS FROM ANYWHERE" option on the network access page and it worked.
(I think it is safe: "Allow access from anywhere" MongoDB Atlas)
I am a beginner here.
I am currently setting up my goorm IDE and trying to connect MongoDB Atlas.
However, I couldn't connect my MongoDB Atlas cluster to my goorm IDE which shows the below message:
ERROR failed to connect to server [cluster0-shard-00-00-1kwgi.mongodb.net:27017] on first connect [MongoError: bad auth Authentication failed.]
I have tried to whitelist the IP with 0.0.0.0/0 as followed the tutorial of Ian Schoonover. However, I still could not connect my MongoDB Atlas.
Below is my code in IDE
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
mongoose.connect('mongodb+srv://dylanOh:123456#cluster0-1kwgi.mongodb.net/test?retryWrites=true&w=majority',{
useNewUrlParser : true,
useCreateIndex : true
}).then(()=>{
console.log('Connected to DB!');
}).catch(err=>{
console.log('ERROR',err.message);
});
app.use(bodyParser.urlencoded({extended: true}));
app.set('view engine', 'ejs');
//Below is my testing info before setting up the database
const campgrounds =[
{name: 'Shenandoah', image:'https://www.nps.gov/shen/planyourvisit/images/20170712_A7A9022_nl_Campsites_BMCG_960.jpg?maxwidth=1200&maxheight=1200&autorotate=false'},
{name: 'Mount Rainier', image:'https://www.nps.gov/mora/planyourvisit/images/OhanaCampground2016_CMeleedy_01_web.jpeg?maxwidth=1200&maxheight=1200&autorotate=false'},
{name: 'Florida', image:'https://www.visitflorida.com/content/visitflorida/en-us/places-to-stay/campgrounds-florida/_jcr_content/full_width/vf_image.img.1280.500.jpg'}]
app.get('/',(req, res)=>{
res.render('landing');
});
app.get('/campgrounds', (req,res)=>{
res.render('campgrounds', {campgrounds:campgrounds});
});
app.post('/campgrounds', (req,res)=>{
const name=req.body.name ;
const image=req.body.image;
const newCampground = {name:name, image:image}
campgrounds.push(newCampground);
res.redirect('/campgrounds');
});
app.get('/campgrounds/new', (req,res)=>{
res.render('new');
});
app.listen('3000', ()=>{
console.log('YelpCamp has started!');
});
As an expected outcome, it should be showing 'Connected to DB!' at my terminal.
However, 'ERROR failed to connect to server [cluster0-shard-00-00-1kwgi.mongodb.net:27017] on first connect [MongoError: bad auth Authentication failed.]' was shown.
I suggest you to create a new db user since the error is an authentication error, you might forget your first created db user's password, I sometimes forget it when I first create the user :)
You see “test?” in url ? That must be replaced with the name of collection you try to connect to.
I am trying to set up my node js application to connect to a MongoDB Atlas database, I am using the full driver code which they have provided me with. But when I start the app I receive the following error:
(node:4195) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Parameter "url" must be a string, not function
Here is the code that I have for my app.js:
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose"),
method_override = require("method-override");
// mongoose.connect("mongodb://localhost/art_eng");
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(method_override("_method"));
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://boris:<passwordWasHere>#arteng-jvhbz.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
And the portfolio page that I have that is connected to the database cannot load and times out. How can I fix it?
I was also facing the same issue but resolved.
Your password must not contains any character which is problematic while parsing.
In my case it just solved by removing % character.
I'm trying to send some data to a database using mongoose. Here is my code so far.
server.js
var express = require('express');
var wine = require('./routes/wines');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.get('/wines', wine.findAll);
app.get('/wines/:id', wine.findById);
app.listen(3000);
console.log('Listening on port 3000...');
wine.js (inside models folder)
var mongoose = require('mongoose');
var db = mongoose.connection;
var wineSchema = new mongoose.Schema({
name: String,
description: String
});
var Wine = mongoose.model('Wine', wineSchema);
module.exports = Wine;
wines.js (inside routes folder)
exports.addWine = function(req, res) {
// Problem not defined here
var silence = new Wine({ name: 'Silence', description:"cena" })
console.log(silence.name) // 'Silence'
// add it to the database
};
I keep getting this error and i have no idea why.
ReferenceError: Wine is not defined
I've exported Wine in wine.js (models), shouldn't I be able to use it everywhere ?
Thank you in advance !
Add var Wine = require('./../models/wine.js'); at the beginning of wines.js (assuming your routes and models folders are contained within the same directory).
Exporting objects/values/functions from node modules does not make them globally available in other modules. The exported objects/values/functions are returned from require (reference here for more info). That said, Mongoose uses an internal global cache for models and schemas which make it available via mongoose (or a connection) throughout an app.
So in your routes file you could do something like:
var Wine = mongoose.model('Wine'); // Notice we don't specify a schema
exports.addWine = function(req, res) {
var silence = new Wine({ name: 'Silence', description:"cena" })
console.log(silence.name) // 'Silence'
// add it to the database
};