this is my code
const mongoose = require('mongoose')
mongoose.connect("mongodb://localhost:27017/fruitsDB", {useNewUrlParser: true, useUnifiedTopology: true}
,(err)=>{
if (err){
console.log(err)
}else {
console.log("Succefully connected")
}
});
const fruitSchema = new mongoose.Schema({
name: String,
rating: Number,
review: String,
});
const Fruit = mongoose.model("Fruit",fruitSchema)
const fruit = new Fruit({
name: "Apple",
rating: 7,
review: "Pretty solid as a fruit"
}
)
fruit.save().then(r => console.log("fruit saved"))
const express = require("express")
const app = express()
app.listen(3000,()=> {
console.log("Server running on port 3000")
});
And this is the error
PS C:\Users\elcha\WebstormProjects\moDB> node app.js
Server running on port 3000
C:\Users\elcha\WebstormProjects\moDB\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:153
const err = new MongooseError(message);
^
MongooseError: Operation `blogs.insertOne()` buffering timed out after 10000ms
at Timeout.<anonymous> (C:\Users\elcha\WebstormProjects\moDB\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:153:23)
at listOnTimeout (node:internal/timers:564:17)
at process.processTimers (node:internal/timers:507:7)
Node.js v18.12.1
The Mongo db is running and conncted,and when I run in terminal - "node app.js"
I recive the error above
How can I solve this problem (without using Atlas cloud) please...
Related
[nodemon] restarting due to changes...
[nodemon] starting node server.js
Server is running on port: ${port}
D:\Practice\mern\mern-exercise\backend\node_modules\mongodb\lib\connection_string.js:290
throw new error_1.MongoParseError(${optionWord} ${Array.from(unsupportedOptions).join(', ')} ${isOrAre} not supported);
^
MongoParseError: option usecreateindex is not supported
at parseOptions (D:\Practice\mern\mern-exercise\backend\node_modules\mongodb\lib\connection_string.js:290:15)
at new MongoClient (D:\Practice\mern\mern-exercise\backend\node_modules\mongodb\lib\mongo_client.js:64:63)
at D:\Practice\mern\mern-exercise\backend\node_modules\mongoose\lib\connection.js:801:16
at new Promise ()
at Connection.openUri (D:\Practice\mern\mern-exercise\backend\node_modules\mongoose\lib\connection.js:798:19)
at D:\Practice\mern\mern-exercise\backend\node_modules\mongoose\lib\index.js:380:10
at D:\Practice\mern\mern-exercise\backend\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
at new Promise ()
at promiseOrCallback (D:\Practice\mern\mern-exercise\backend\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (D:\Practice\mern\mern-exercise\backend\node_modules\mongoose\lib\index.js:1225:10) {
[Symbol(errorLabels)]: Set(0) {}
}
Node.js v18.7.0
[nodemon] app crashed - waiting for file changes before starting...
And the code is
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express ();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {useNewUrlParser: true, useCreateIndex: true}
);
const connection = mongoose.connection;
connection.once('open', ()=>{
console.log("MongoDB database connection established successfully");
})
app.listen(port, () => {
console.log('Server is running on port: ${port}')
});
process.on('warning', e => console.warn(e.stack));```
According to the mongoose docs
useCreateIndex isn't an option to mongooose.connect()
im a bloody beginner in the node.js, mongo.db topic, i made some courses and now i want to combine those, but when i require my mongodb database, my index.html isnt available anymore on the localhost 3000:
when i comment those line out my localhost connection work:
app.use(require('./routes/posts'));
i think i made something in the inizialisation wrong, but im a bloody beginner, i have no idea what i did wrong.
my server.js:
const express= require('express')
const app= express();
const http= require('http').createServer(app)
const PORT=process.env.PORT || 3000
http.listen(PORT, ()=>{
console.log(`listening to port ${PORT}`)
})
app.use(express.static(__dirname + '/public'))
app.use(require('./routes/posts'));
app.get('/',(req,res)=>{
res.sendFile(__dirname + '/index.html')
})
//socket implementation
const io=require('socket.io')(http)
io.on('connection',(socket)=>{
console.log('connected')
socket.on('message', (msg)=>{
socket.broadcast.emit('message',msg)
})
})
routes/posts.js:
const express= require('express');
const router=express();
const Post=require('../model/post');
router.use(express.json);
router.post('/posts/new', (req,res)=>{
const post = new Post({
title:req.body.title,
content: req.body.content
})
post.save()
.then(result=> res.sendStatus(201))
.catch(err=>{
console.log(err);
res.status(500).json({error:err})
})
})
module.exports=router;
model/post.js:
const db= require('../database');
const postSchema= new db.Schema({
title: {type: String, require:true},
content: {type: String, require:true}
}, {timestamps:true});
const Post= db.model("Post", postSchema);
module.exports=Post;
database.js:
const mongoose= require('mongoose');
//const mongoose = require('mongoose/browser');
mongoose.connect('mongodb://localhost/accounts', ()=>{
console.log('mongodb connected');
})
module.exports=mongoose;
test.rest:
GET http://localhost:3000/
POST http://localhost:3000/posts/new
Content-Type: application/json
{
"title": "first",
"content": "test"
}
i want to achieve that i can use the post command in test.rest and it writes those into my local mongo db, while i can see on localhost 3000 the frontend.
thanks for help!
I am building a RESTful BLogAPP where my stack is MEN
while connecting to mongo server i am getting this error
These were working But this happened
My Mongo file code
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const url = "mongodb://localhost/127.0.0.1:27017/Blog";
mongoose.connect(url ,{
useNewUrlParser: true,
useUnifiedTopology: true
})
const db = mongoose.connection;
db.once("open", (_) => {
console.log("Database connected:", url);
});
db.on("error", (err) => {
console.error("connection error:", err);
});
module.exports = mongoose;
My app.js
const mongoose = require("./server/mongoose");
It was resolved for me after remove server port from connection string. Replace mongodb connection string From
const url = "mongodb://localhost:27017/Blog";
To
const url = "mongodb://localhost/Blog";
I got the same error message and I've finally solved it. Try to leave it like this:
const url = "mongodb://localhost:27017/Blog";
I too got the same error while accessing MongoDB via mongoose.
The URI I set was MONGO_URI=mongodb://localhost:3000/myDB.
The port was wrong.
I solved it by correcting the Mongo URI.
MONGO_URI=mongodb://localhost:27017/myDB.
I'm new in the MEAN developing, I'm developing a simple app, and for my first step I'm trying to connect to my mongodb, so I installed node, express, morgan,mongodb, mongoose.
So here is my code in index.js:
const express = require('express');
const morgan = require('morgan');
const app = express();
const { MongoClient } = require('./database');
// Settings
app.set('port', process.env.PORT || 3000);
// Middlewares
app.use(morgan('dev'));
app.use(express.json());
// Routes
// Starting the server
app.listen(app.get('port'), () => {
console.log('server on port', app.get('port'));
});
and then the code on my database.js:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://duke:<password>#cluster0-dreyi.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
console.log("horrorrrrrr");
// perform actions on the collection object
client.close();
});
module.exports = MongoClient;
I also try this code that is on the mongodb page to connect to the application:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://duke:<password>#cluster0-dreyi.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();
});
Of course I change the password to the real one. Please keep in my today it's my first time I touch mongodb and also the MEAN full stack, and I spent too many hours stuck in this connection.
this is the error I get:
(node:5284) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
EDIT
#iLiA thanks for your reply ! I tried your code and ain't working, I will show you how I did it with the real password :
const url = 'mongodb+srv://duke:password#cluster0-dreyi.mongodb.net/test?retryWrites=true&w=majority';
const mongoose = require('mongoose');
mongoose.connect(url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
})
.then(()=>{
console.log('congrats, problem solved')
})
.catch((err)=>{
console.log(`there is not a problem with ${err.message}`);
process.exit(-1)
})
module.exports = mongoose;
and the error is :
there is not a problem with Server selection timed out after 30000 ms
[nodemon] app crashed - waiting for file changes before starting...
Kind regards,
I am confused about why do you downloaded both mongodb and mongoose but here is mongoose solution
const mongoose = require('mongoose');
mongoose.connect(url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
})
.then(()=>{
console.log('congrats, problem solved')
})
.catch((err)=>{
console.log(`there is a problem with ${err.message}`);
process.exit(-1)
})
EDIT:
As it seems you forgot to whitelist your IP address in mongo atlas.
I can't connect to the mongoDB, this is the error I'm getting each time:
[nodemon] 1.19.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
Server started on port 5000
Server selection timed out after 30000 ms
[nodemon] app crashed - waiting for file changes before starting...
Already tried:
- changing ip access on mongoDB from everywhere to current ip adress and otherwise,
- creating new account that was for sure made on my current ip adress,
- disabling firewall,
- checked code for errors,
- tried restarting my pc for some reason
here is my code
//////server.js/////
const express = require('express');
const connectDB = require('./config/db');
const app = express();
// Connect Database
connectDB();
app.get('/', (req, res) =>
res.json({ mgs: 'Welcome to the ContactKeeper API...' })
);
// Define Routes
app.use('/api/users', require('./routes/users'));
app.use('/api/auth', require('./routes/auth'));
app.use('/api/contacts', require('./routes/contacts'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
//////default.json/////
{
"mongoURI": "mongodb+srv://artur123:<artur123>#contactkeeper-lv2py.mongodb.net/test?retryWrites=true&w=majority"
}
//////db.js/////
const mongoose = require('mongoose');
const config = require('config');
const db = config.get('mongoURI');
const connectDB = () => {
mongoose
.connect(db, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
})
.then(() => console.log('MongoDB Connected'))
.catch(err => {
console.error(err.message);
process.exit(1);
});
};
module.exports = connectDB;
You just have to add your ip in the ip whitelist on mongoDB Atlas under :
Network Access
then restart.