I use nodejs express and mongoose to connect mongodb,I've created a config.js in root folder.I am trying to exports db connect in db.js and trying to import in adminController.js
But when I run the server and refresh the browser ,it log me some errors and not log my log in terminal.
config.js
module.exports = {
cookieScret:'ThreeKingdoms',
db:'threekingdoms',
host:'localhost',
port:27017
}
db.js
var mongoose = require('mongoose'),
config = require('../config'),
connection = mongoose.connection;
module.exports = function(mongoose){
return mongoose.connect('mongodb://'+config.host+'/'+config.db);
}
adminController.js
var express = require('express'),
router = express.Router(),
mongoose = require('mongoose'),
mainInfo = require('../models/admin'),
db = require('../models/db');
router.get('/', function(req, res) {
res.render('admin', { title: 'hey im here!how are you' });
db.on('error',console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log(db)
});
console.log(db)
});
router.post('/',function(req,res,next){
//console.log(req.body)
var mainInfo = mongoose.model('mainInfo');
})
module.exports = router;
question files is in red box
terminal error
I am new to nodejs,so please help me,Thanks
First, it seems that you don't have kerberos installed. Please run npm install kerberos.
Also, the line
Can't set headers after they're sent
Suggests you're trying to modify/send the response after it was already sent back to the client, and that's the error you're getting.
finally it is work now,but it doesn't matter with 'kerberos' ,it is i use wrong way to export my module.terminal still log me 'kerberos undefined' but web can work,i think maybe some time i will try to figure this question out.thanks for your attention
Related
I implemented express code with the mongoose database but I have faced "nodemon crushed" error for that I followed the below techniques but still, now I have faced this error.
Node version: v16.14.2
NPM version: 8.5.0
I have followed some steps to solve this issue and that is given below,
Open Windows Task Manager is given in the attached file
End Task (Node.js JavaScript Runtime)
But the problem is not solved!
Here is the code of server.js
const express = require('express')
const mongoose = require('mongoose')
const app = express()
mongoose.connect('mongodb://localhost:27017/my-students');
const studentRoute = require('./api/routes/studentsRoute');
//========> Routing Starting
app.use('/api/students', studentRoute);
//========> Routing End
//========> MongoDB Database connection and Check
const db = mongoose.connection;
db.on('error', (err) =>{
console.log(err);
})
db.once('open', ()=>{
console.log("Database connection Established!")
})
const PORT = process.env.PORT || 3000;
app.listen(PORT, () =>{
console.log(`Server running on PORT #${PORT}`)
})
Windows Task Manager where I end the task by clicking "End Task" of "Node.js JavaScript Runtime" but it was not solved the issue and the Task Manager file attached below,
Error screenshot is given below the attached file,
The problem is arising from this line
const studentRoute = require('./api/routes/studentsRoute');
check if you have this included in that file
module.exports = router
Reference: TypeError: Router.use() requires middleware function but got a Object
I am writing a code that allows me to connect to the MongoDB database that I had made. For some reason, I am getting errors connecting my page and I don't know why. I have already looked at TypeError: connection.once(...).catch is not a function for help but that page did not answer my question. I also copied the code that my professor made and I can't seem to get it working.
This is my code:
const express = require('express');
const app = express();
const connection = require('./db/connection.js');
const dotEnv = require('dotenv').config();
connection.once('open', ()=>{
const server = app.listen(process.env.PORT || 8080, ()=>{
console.log("Connected and listening");
});
});
app.use(express.static('public'));
app.use(express.urlencoded({extended:true}));
const Film = require('./models/film.js');
And this one is the connection.js file
const mongoose = require("mongoose");
let mongoDB = `name of database (this is correct, I used this to connect to a different project and it worked`;
module.exports = mongoose.connect(mongoDB);
hy, I'm learning nodeJS but when do post using postman data is saving in db but not displaying response in POSTMAN. On postman just displaying sending request... .
const express = require("express")
const app = express()
// dbConnection
require('./mongo')
// Models
require('./model/Post')
// MIDDLEWARE
app.use(express.urlencoded({extended: true}));
app.use(express.json())
const mongoose = require('mongoose')
const Post = mongoose.model("Post")
// POST REQUEST
app.post('/posts', async (req, res)=>{
// res.send(req.body)
try{
const post = new Post()
post.title = req.body.title
post.content = req.body.content
data = await post.save()
res.json(data)
}catch(error){
res.status(500)
}
})
app.listen(8000, ()=>{
console.log('Server is running on port:8000')
})
I don't think you're even running on a port, it says here
console.log('Server is running on port:8000')
})
All you do is console.log Server is running on Port 8000 with no back tick, therefore your not even running your server. This is why I think your Code is not working, test it out and see, if you get an error then you can debug from there. At least put some effort into debugging rather than immediately going on stack overflow. replace what you done with the port with this
// Create a variable called port and set it to your desired port
const port = 8000;
// Then hook it up to express.
console.log(`Server is running on port: ${port}`)
})
If the problem is still there then I think I have the solution to it
Check if you have mongoose and express installed
(it's npm i mongoose express)
I don't think you're even connected to your mongoose server, try doing this
const express = require("express")
const app = express()
// dbConnection
require('./mongo')
// Models
require('./model/Post')
// MIDDLEWARE
app.use(express.urlencoded({extended: true}));
app.use(express.json())
const mongoose = require('mongoose')
const Post = mongoose.model("Post")
// Hook it up to res
const port = 8000
// POST REQUEST
app.post('/posts', async (req, res)=>{
// res.send(req.body)
try{
const post = new Post()
post.title = req.body.title
post.content = req.body.content
data = await post.save()
res.json(data)
}catch(error){
res.status(500)
}
})
// Mongoose Connection
mongoose
.connect("your connection (it should be connection to application on mongo)", {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: true
})
.then(() => {
console.log("Connected to the database");
})
.catch((err) => {
console.log(err);
});
app.listen(8000, ()=>{
console.log(`Server is running on port: ${port}`)
})
Then once you've finished that, you established a connection to the mongodb server and should send the request to post
I think the catch block is executed. In this block, you only set the status of the response to 500 but you don't actually send the response to the client. That's why the Postman screen keeps blocking.
So, there are 2 things:
you need to send something to the client
you need to log the error to debug.
app.post('/posts', async (req, res)=>{
// res.send(req.body)
try{
const post = new Post()
post.title = req.body.title
post.content = req.body.content
data = await post.save()
res.json(data)
}catch(error){
console.log(error);// for debugging
res.status(500).send("ERROR_SERVER"); // send something to client
}
})
I have found the answer for your error, as I said in my old answer, running your tests would've worked, and showed you the error, however I have found the answer, I am assuming you have already found the solution (which is probably the same solution as mine) but if you haven't here's the problem.
The problem
It's very simple, you're creating a variable for mongoose after you required mongoose require('./mongo'); const mongoose = require('mongoose') This is wrong as JavaScript and most programming languages read code line by line (if not then all) so change this up to be instead the following:
Solution
const mongoose = require('mongoose');
require('./mongo');
Information
Create the variable before you require the package like so (in your code example):
const mongoose = require('mongoose');
require('./mongo');
If you have more problems
If you do have more problems then try to reinstall/update the package dependency for mongoose as following:
yarn add mongoose
or
npm install mongoose
If you do still have problems after the only think I can ask you to do is to change the line of code when it says
require('./mongo');
to either
require('./{filename}'); // Whatever the actual filename is.
or:
require('./mongoose');
Tips to improving your question
Even if my question doesn't work for your code make sure to paste the error message or the important parts of the error message into the question, otherwise this makes it hard to pinpoint what your error is. This makes it easier to find the solution for your code.
I have a question about the require function of Node.js, imagine we have a module that manages the connection, and many small modules that contain the routes.
An example of connection file: db.js
const mysql = require('mysql');
const connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'chat'
});
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
and one of the various files to manage the routes:
const app = express();
const router = express.Router();
const db = require('./db');
router.get('/save',function(req,res){
// some code for db
});
module.exports = router;
Imagine now to have 20 routes with the same require. How will node.js behave? How many times will my connection be created?
How many times will my connection be created?
There will be one connection, because "db.js" runs only once. The things you export get stored (module.exports) and that gets returned by every require("./db"). To verify:
require("./db") === require("./db") // true
I keep getting an error when trying to connect mongoDB. I know there are many questions similar to this one and I have checked all of them and haven't found a solution for my issue.
Here is the exact error:
connection error: { MongoError: connect ECONNREFUSED 127.0.0.1:21017
name: 'MongoError'
message: connect ECONNREFUSED 127.0.0.1:21017
I looked at some other solutions and they say to adjust the mongo.conf file but I can't seem to find the file on my system and I've downloaded MongoDB.
Here is my full code:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
$ = require('cheerio');
/* GET home page. */
mongoose.connect('mongodb://localhost/');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('Connected to database');
// we're connected!
});
var pageInfo = {
title: 'JotIT',
owner: 'Emmanuel Obogbaimhe',
message: 'Hi welcome to JotIT. A quick, simple and easy to use note taker.',
date: Date.now(),
age: 22
};
router.get('/', function(req, res, next) {
res.render('index', {
title: pageInfo.title,
author: pageInfo.owner,
message: pageInfo.message,
date: pageInfo.date,
age: pageInfo.age
});
});
module.exports = router;
The reason for getting that kind of error: {MongoError: connect ECONNREFUSED 127.0.0.1:21017}, is that Mongo process is not running on that PORT, or not running at all.
For first check out if mongo process is running:
service mongod status //for Linux machine
For second - check the port of mongo process:
nmap -p- localhost //for Linux machine
For windows, open another terminal and cd into the apps root directory. Then, run $ mongod.exe. I would recommend placing the following into a test.js file:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test.js');
var db = mongoose.connection;
db.on("error", function(error){
console.error("Connection error : " + error)
});
db.once('open', function() {
console.log('Connected to database');
db.close(function(){
console.log("db connection closed");
});
});
Go back to the original terminal and run $ node test.js
I had the same error, It looks like and bad closing in preview mongodb session I just did and It worked out fine
sudo service mongod stop
sudo service mongod start
Had the same problem, caused by running out of hard drive memory space. This caused mongod to keep crashing after restarting it.
Simply increasing memory space of the server, and restarting mongod (either manually or via reboot when service restarts automatically) solved the issue.
Try this
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
$ = require('cheerio');
/* GET home page. */
mongoose.connect('mongodb://localhost:27017/db-dev');
or try with
mongoose.connect('mongodb://0.0.0.0:27017/db-dev');
change your mongoose connection code to:
mongoose.connect('mongodb://localhost:27017/yourdb');
This error can be solved by replacing localhost in the following code with the address of localhost which is 127.0.0.1.
mongoose.connect('mongodb://localhost/');
Try this -> mongoose.connect('mongodb://127.0.0.1/');