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!
Related
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...
I am trying to connect to MongoDB but I am getting the "Password contains unescaped characters" error. I have included the useNewUrlParser:true option but I still get the error
See my code below:
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
dotenv.config();
connectDB().catch(err => console.log(err));
async function connectDB() {
await mongoose.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
})
.then(() => console.log("DB Connection Success"))
.catch((err) => console.log(err));
}
app.listen(8800, () => {
console.log("Backend Server is running");
});
Same problem here... solved with encodeURIComponent on the part of the string that had the password
const uri = "mongodb+srv://username:" + encodeURIComponent("pass#") + "#cluster.yijnb.mongodb.net/db?retryWrites=true&w=majority";
Maybe provide username and password as option:
const options = {
user: <username>,
pass: <password>,
authSource: "admin",
useNewUrlParser: true
};
mongoose.connect(process.env.MONGO_URL, options);
I solved it by changing the password as I tried using several fixes to help me connect with the initial password that contained ".".
Having an issue connecting to MongoDB when starting a new MERN stack project:
server.js code:
const express = require('express');
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, { useUnifiedTopology: true, useNewUrlParser: 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}`);
});
.env file:
ATLAS_URI = mongodb+srv://exampleUser:exampleUserPassword#cluster0.y9bpc.mongodb.net/example-
database?retryWrites=true&w=majority
receiving error:
(node:23036) UnhandledPromiseRejectionWarning: MongoError: Authentication failed.
Not sure what I'm doing wrong here, was just following a tutorial. Only difference from the tutorial is the connection string which also requires a dbname which I created and added. I'm hoping it's something more simple than that. I appreciate any help.
So it appears that I chose to add my own IP address instead of allowing access from anywhere and that was the issue. Hooray!
First time using mongoDB. Trying to connect to my cluster that i just created on atlas however i keep getting errors
keys.jss
module.exports = {
mongoURI: 'mongodb+srv://john:<********>#mern-shopping-i5abd.mongodb.net/testretryWrites=true&w=majority'
};
I might be following an outdated tutorial so certain things might be 'unnecessary'
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
// Bodyparser Middleware
app.use(bodyParser.json());
// DB config
const db = require('./config/keys').mongoURI;
// Connect to Mongo
mongoose
.connect(db, {useNewUrlParser: true} )
.then(() => console.log('monogoDB Connected...'))
.catch(err => console.log(err));
const port = process.env.PORT || 5000;
app.listen(port, () => console.log('Server started on port ${port}'));
Rather than displaying port '5000' i would get an error (different each time)
message: '3rd parameter to mongoose.connect() or mongoose.createConnection() must be a function, got "object"',
name: 'MongooseError'
Here is how it would look with a function as a callback, instead of using promises. Notice that I also moved the app startup inside the callback function. This ensures that the app only starts up when we successfully connect to the DB.
I also moved the DB options (2nd parameter in the connect method), into a variable. This way, it's easy to find and can be modified in one place, if necessary. Ideally, you'd keep all your DB config in a single file, and reference it in other files as needed. Separate concerns :)
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
// Bodyparser Middleware
app.use(bodyParser.json());
// DB config
const db = require('./config/keys').mongoURI;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
// Connect to Mongo
mongoose
.connect(db, dbOptions, function(error) {
// we had an error of some kind
if (error) {
console.error(error);
// better yet, we don't want to app to run without our DB!
throw error;
}
// If we made it here, no errors came up
console.log('monogoDB Connected...');
// Start up the app!
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
});
Here is how it would look with the promise structure:
const express = require( "express" );
const mongoose = require( "mongoose" );
const bodyParser = require( "body-parser" );
const app = express();
// Bodyparser Middleware
app.use( bodyParser.json() );
// DB config
const db = require( "./config/keys" ).mongoURI;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
// Connect to Mongo
mongoose
.connect( db, dbOptions )
.then( () => {
console.log( "monogoDB Connected..." );
// Start the application
const port = process.env.PORT || 5000;
app.listen( port, () => {
console.log( `Server started on port ${port}` );
} );
} )
.catch( err => {
console.log( err );
throw err;
} );
const express = require('express');
const exphbs = require('express-handlebars');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
// Connect to mongoose
mongoose.connect('mongodb://localhost:27017/sample')
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
app.get('/', (req, res) => {
const title = 'Welcome';
res.send('ok');
});
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
I have written this code to connect MongoDB and there is no issue with the connection but when I show my DBS using "> show dbs", I can't see the sample database which I have created. My system is windows 32 bit.
Just connecting to the database won't create it. You need to add something to the database like saving a new document or adding an index.