I have a problem with my code I used this code in
app.js:
const mongoose = require('mongoose');
const dotenv = require('dotenv');
dotenv.config()
mongoose.connect(process.env.MONGO_URL)
.then(() => console.log("DB connected!"));
mongoose.connection.on('error',function(err){
console.log("The error is: ");
});
env.txt:
MONGO_URL=mongodb+srv://blur:blur#nodeapi-pfnvf8.mongodb.net/test?retryWrites=true
PORT:8080
and for some reason it's giving me this weird error:
throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
^ 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.
at new MongooseError (C:\Users\razei\Desktop\Recat\project2\node_modules\mongoose\lib\error\mongooseError.js:14:11)
at NativeConnection.Connection.openUri (C:\Users\razei\Desktop\Recat\project2\node_modules\mongoose\lib\connection.js:465:11)
at Mongoose.connect (C:\Users\razei\Desktop\Recat\project2\node_modules\mongoose\lib\index.js:289:15)
at Object.<anonymous> (C:\Users\razei\Desktop\Recat\project2\ap.js:9:10)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3) [nodemon] app crashed - waiting for file changes before starting...
can someone please help me I read a few posts but none of them helped
This also occurs when you aren't saving your .env file in the root folder.
Save your env file as .env not env.txt and make sure it's in your root folder as well & see if that works! Also MONGO_URI is the traditional naming convention but that shouldn't matter.
mongoose
.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
})
.then(() => {
console.log('Connected to Mongo!');
})
.catch((err) => {
console.error('Error connecting to Mongo', err);
});
Additionally you can simplify your 2 require statements above with the lines below and you should call this as soon as possible:
require('dotenv').config();
const mongoose = require('mongoose')
Require dotenv like this. It worked for me
require('dotenv').config();
first of all, the env file should be saved as .env not env.txt, .txt is an extension for text files.
Also, I don't think you have named your project 'test' so make sure to change it to your current project name.
If you still get an error, do not use environment variables instead add the whole mongodb path inside mongoose.connect() in double or single quotes.
mongoose.connect(process.env.mongodb, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
});
I too was getting the same errors, It was crashing due to the environment variable MONGODB_URI not being set and running heroku config returned with no variables in the cli.
The fix was running : heroku addons:create mongolab:sandbox
If heroku push origin master is needed, then heroku config should now show your .env variable.
The error comes when we put our database credentials in .env file and in main file of server we create connection before .env file, instead we should create connection after requiring .env file.
I encountered this error as well, The first thing you need to do is to place your .env file in the "ROOT FOLDER". This will solve your issue.
was having the same error.. :
This also worked for me..
require('dotenv').config();
checkout this post for more info : https://dev.to/aritik/connecting-to-mongodb-using-mongoose-3akh
Make sure the root folder is where config.env is created and that the right path is specified for # app.js => dotenv.config(path: "./config.env").
dotenv.config({ path: "./config.env" });
const dotenv = require('dotenv');
dotenv.config({path:'config.env'});
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true
});
I fixed that myApp.js file code
config.env file code
package.json file
"name": "fcc-mongo-mongoose-challenges",
"version": "0.0.1",
"description": "A boilerplate project",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"body-parser": "^1.15.2",
"dotenv": "^8.2.0",
"express": "^4.12.4",
"mongodb": "^4.12.1",
"mongoose": "^5.11.15"
},
"repository": {
"type": "git",
"url": "https://github.com/freeCodeCamp/boilerplate-mongomongoose.git"
},
"keywords": [
"node",
"mongoose",
"express"
],
"license": "MIT"
}
Please check above two screenshots to solve this problem
Hope this will be help to anyone
Related
I'm new to Node.js, please help me.
What is wrong?
Using typescript, SQLite3 and Knex, with migration.
I get the error when running "yarn knex: migrate" or "knex migrate: latest":
$ knex migrate:latest
Requiring external module ts-node/register
Error: knex: Required configuration option 'client' is missing
These are my files:
package.json:
{
"name": "backend",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "ts-node-dev --transpile-only --ignore-watch node-modules --respawn
src/server.ts",
"knex:migrate": "knex --knexfile knexfile.ts migrate:latest",
"knex:migrate:rollback": "knex --knexfile knexfile.ts migrate:rollback"
},
"devDependencies": {
"#types/express": "^4.17.11",
"ts-node": "^9.1.1",
"ts-node-dev": "^1.1.6",
"typescript": "^4.2.4"
},
"dependencies": {
"espress": "^0.0.0",
"express": "^4.17.1",
"knex": "^0.95.4",
"sqlite3": "^5.0.2"
}
}
knexfile.ts:
import path from'path';
module.exports = {
cliente: 'sqlite3',
connection: {
filename: path.resolve(__dirname, 'src', 'database', 'resp.sqlite')
},
migrations: {
directory: path.resolve(__dirname, 'src', 'database', 'migrations'),
},
useNullAsDefault: true,
};
Migration 00_create_organizacoes.ts:
import knex from 'knex';
export async function up(knex: knex) {
return knex.schema.createTable('organizacoes', table => {
table.increments('id').primary();
table.string('razaosocial_org').notNullable();
table.integer('atividade_org').notNullable();
table.timestamp('criacao_org').defaultTo(knex.fn.now());
table.timestamp('atualizacao_org').defaultTo(knex.fn.now());
});
}
export async function down(knex: knex) {
return knex.schema.droptable('organizacoes');
};
My file structure:
enter image description here
Unsuccessful in other treatments.
Looks like you have a typo in your knexfile.ts
The name of the missing property is client and not cliente
The Requiring external module ts-node/register message you get is not the issue, the issue is that in the knexfile.ts the client property is not read. From the example above change the cliente property to client and it is fixed.
What if you have no spelling error, client exist in your configuration, and you are getting this message? Are you using a env file? If yes, In your knexfile.ts print the value from your env file. If it returns undefined, it means that no value was read for the env file. Check if you have the dotenv package installed and configured properly. Also check that your env file has a key called client and the value is available and in the knexfile.ts ensure you are calling the right key from your env.
Finally if the problem is not solved and every other thing is in-place, require dotenv in your package.json file before running a command as shown below.
"migrate:latest": "ts-node -r dotenv/config ./node_modules/knex/bin/cli.js migrate:latest
The ts-node -r dotenv/config ensures that the details in the env file are added to the environment.
The ./node_modules/knex/bin/cli.js starts the knex cli so that the remaining part which is a knex command can be executed.
I just started using nodemon and strtaed creating a very small example project.
However, as soon as I launch the server sudo npm run dev I get the following error:
[nodemon] app crashed - waiting for file changes before starting...
The error says that there is a mistake on users.js:7 app.use(expressLayouts);
emanuele#pc:~/Desktop/dashboard$ sudo npm run dev
dashboard#1.0.0 dev /home/emanuele/Desktop/dashboard
nodemon app.js
[nodemon] 2.0.2 [nodemon] to restart at any time, enter rs [nodemon]
watching dir(s): . [nodemon] watching extensions: js,mjs,json
[nodemon] starting node app.js
/home/emanuele/Desktop/dashboard/routes/users.js:7
app.use(expressLayouts);
^
ReferenceError: app is not defined
at Object. (/home/emanuele/Desktop/dashboard/routes/users.js:7:1)
at Module._compile (internal/modules/cjs/loader.js:955:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Module.require (internal/modules/cjs/loader.js:848:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object. (/home/emanuele/Desktop/dashboard/app.js:7:19)
at Module._compile (internal/modules/cjs/loader.js:955:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10) [nodemon] app crashed -
waiting for file changes before starting...
So below is where the error should be:
app.js
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const app = express();
app.use(expressLayouts);
app.set('view engine', 'ejs');
// Routes
app.use('/', require('./routes/index'));
app.use('/users', require('./routes/users'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`Server started on port ${PORT}`));
index.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => res.render('welcome'));
module.exports = router;
users.js
const express = require('express');
const router = express.Router();
// Login Page
router.get('/login', (req, res) => res.send('Login'));
// Register Page
router.get('/register', (req, res) => res.send('Register'));
module.exports = router;
If needed below my package.json
{
"name": "dashboard",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "node app.js",
"dev": "nodemon app.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"connect-flash": "^0.1.1",
"ejs": "^3.0.1",
"express": "^4.17.1",
"express-ejs-layouts": "^2.5.0",
"express-session": "^1.17.0",
"mongoose": "^5.8.11",
"passport": "^0.4.1",
"passport-local": "^1.0.0"
},
"devDependencies": {
"nodemon": "^2.0.2"
}
}
I don't understand what is wrong in the above piece of code.
I consulted some posts such as:
1) This but could't solve the problem
2) This one too but no success
3) I consulted this source
4) I came across this too but could still not figure out what could be wrong
Thanks for pointing in the right direction to understand where the error could be.
Inside index.js (and users.js) there is no app variable defined:
app.use(expressLayouts);
app.set('view engine', 'ejs');
These should be defined in app.js where you have this definition const app = express();. They will then apply for all other routes in your Express application, so defining them multiple times is not needed.
i tried to generate reports by using "'protractor-jasmine2-html-reporter'", but i'm getting module not found exception with error code 5..i tried the somany solutions gathered from stack overflow, but it is not worked. can somebody please help me in this.
Config.js
var Jasmine2HtmlReporter=require('protractor-jasmine2-html-reporter');
exports.config = {
directConnect : true,
capabilities:{
'browserName':'chrome'
},
framework: 'jasmine2',
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['ProtractorTest/PageObjectMain.js'],
jasmineNodeOpts:{
defaultTimeoutInterval : 30000
},
onPreapre:function(){
jasmine.getEnv().addReporter(new Jasmine2HtmlReporter({
savePath:"./test-results/report"
}));
},
}
Error log
[14:54:53] E/configParser - Error code: 105
[14:54:53] E/configParser - Error message: failed loading configuration file ReportConfig.js
[14:54:53] E/configParser - Error: Cannot find module 'protractor-jasmine2-html-reporter'
at Function.Module._resolveFilename (module.js:538:15)
at Function.Module._load (module.js:468:25)
at Module.require (module.js:587:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (H:\workspace\Protractor_tutorials\ReportConfig.js:1:88)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
and my 'Package.Json' not have any details about the report files.. so if that is the problem, please help me to how to configure those in json file.
There are few things you have to make sure while using Protractor Reporters
1.in my case, in the time creating variable for reporter instead of directly passing Reporter name try to pass the full path of Reporter module.. may this will work
Eg :
var Jasmine2HtmlReporter=require('C:/......./npm-modules/protractor-jasmine2-html-reporter');
2.make sure you running the Correct Configuration file having .js extension.
Installing without save-devworked for me .
Installed globally
npm install -g protractor-jasmine2-html-reporter
Run below command to link protractor and jasmine2-html-reporter to aovid report not generating issue. Please see Girish Sortur's answer in How to create Protractor reports with Jasmine2
npm link protractor-jasmine2-html-reporter
Also add this import with path to exact node module to avoid the error in windows 10
var Jasmine2HtmlReporter = require('C:/Users/sam/AppData/Roaming/npm/node_modules/protractor-jasmine2-html-reporter');
Full conifg,js that worked for me in windows 10 as per below.
//protractor jasminreporterconfig.js
//Add this import with path to exact node module to avoid the error
var Jasmine2HtmlReporter = require('C:/Users/sam/AppData/Roaming/npm/node_modules/protractor-jasmine2-html-reporter');
exports.config = {
framework: 'jasmine',
capabilities: {
browserName: 'chrome',
chromeOptions: {
args: [ "--start-maximized" ]
}
},
onPrepare: function() {
jasmine.getEnv().addReporter(
new Jasmine2HtmlReporter({
takeScreenshots: true,// By default this is enabled Default is true
takeScreenshotsOnlyOnFailures: false, // Default is false (So screenshots are always generated)
cleanDestination: true, // if false, will not delete the reports or screenshots before each test run.Default is true
showPassed: true,//default is true This option, if false, will show only failures.
fileName: 'MyRepoDemo', //We can give a prefered file name .
savePath: 'myproreports',//Reports location it will automatically generated
screenshotsFolder: 'screenshotsloc' //Screenshot location it will create a folder inside myproreports
})
);
},
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['src/com/sam/scriptjs/nonangularstackscript.js']
}
It looks like You haven't installed protractor-jasmine2-html-reporter
Go to folder where packages are installed (node_modules folder) and run:
npm install protractor-jasmine2-html-reporter
Try to check where the node_modules directory is present by running npm audit and which npm commands. The main thing is path where node_modules is installed should be traced and the new module like npm install protractor-jasmine2-html-reporter can be installed in that path
I'm trying to incorporate es6 in my server side code. Using babel-node works when running the server , however i'm having trouble compiling es6 to es5 code when running mocha tests.
This is my folder structure
I have a server.js which starts up a worker.js file(which has the express server)
the server.js file
import {SocketCluster} from 'socketcluster';
const socketCluster = new SocketCluster({
workers:1,
brokers:1,
port: 3000,
appName:null,
workerController: __dirname + '/worker.js',
brokerController: __dirname + '/broker.js',
socketChannelLimit: 1000,
crashWorkerOnError: true
})
the worker.js file
export const run = (worker) => {
console.log(' >> worker PID: ',process.pid);
const app = express();
const httpServer = worker.httpServer;
const scServer = worker.scServer;
app.use(cookieParser())
httpServer.on('request', app);
app.get('/',(req,res) => {
console.log('recieved')
res.send('Hello world')
})
}
When running the server manually , it works with the below script
"start": "nodemon server/server.js --exec babel-node"
however , when i try running the test file with mocha i get an 'unexpected token "export" error'
(function (exports, require, module, __filename, __dirname) { export const run = (broker) => {
^^^^^^
SyntaxError: Unexpected token export
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:511:25)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:456:32)
at tryModuleLoad (module.js:415:12)
at Function.Module._load (module.js:407:3)
at Module.require (module.js:466:17)
at require (internal/module.js:20:19)
at initBrokerServer (/home/avernus/Desktop/projects/node-sc-react/node_modules/sc-broker/server.js:178:25)
at process.<anonymous> (/home/avernus/Desktop/projects/node-sc-react/node_modules/sc-broker/server.js:498:9)
this is the script to start the mocha tests
"test": "mocha test/server/*.js --compilers js:babel-register"
am i missing something else?
this is the test file
import server from '../../server/server';
import http from 'http';
import assert from 'assert';
import {expect} from 'chai';
describe('Express server',() =>{
it('should return "Hello World"',() => {
http.get('http://127.0.0.1:3000',(res) => {
expect(res).to.contain('wtf world')
})
})
})
You need to transpile test scripts from ES2015 to ES5 using Babel before passing it to mocha to run the tests. You can do it as follows adding/editing test script in package.json
...
"scripts": {
"test": "mocha --compilers js:babel-core/register --recursive"
},
...
Update:
Mocha deprecated the --compiler flag. Please check this page for more information. The new npm script should look like below
...
"scripts": {
"test": "mocha --require babel-register --recursive"
},
...
Turns out i need to specify an initController in my server.js file to ensure that all files are compiled by babel. This is a problem specific to the websocket framework i'm using.
I am currently working on an express.js Webapp, Im working off the boilerplate app that comes with MS Webmatrix. I am able to run the app on my computer but when i push to nodejitsu or use another computer from which i got the app from git i get an error preventing server start.
app.use(express.compiler({ src: __dirname + '/public', enable: ['less'] })
^
TypeError: Object function createApplication() {
var app = connect();
utils.merge(app, proto);
app.request = { __proto__: req };
app.response = { __proto__: res };
app.init();
return app;
} has no method 'compiler'
at Function.<anonymous> (C:\Users\hoopdog2\Desktop\afterthoughts_nodejs\serv
er.js:197:21)
at Function.app.configure (C:\Users\hoopdog2\Desktop\afterthoughts_nodejs\no
de_modules\express\lib\application.js:399:61)
at Object.<anonymous> (C:\Users\hoopdog2\Desktop\afterthoughts_nodejs\server
.js:188:5)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
The dependencies that that app uses are
"node-uuid": ">= 1.3.3",
"everyauth": ">= 0.2.29",
"nconf": ">= 0.5.1",
"express": ">= 2.5.0",
"jade": ">= 0.18.0",
"less": ">= 1.1.5",
"socket.io": ">= 0.8.7",
"connect": ">=1.8.5",
"recaptcha": ">=1.1.0"
And i am using node version 0.8.7. Any suggestions to what might be causing this error is greatly appreciated
The compiler middleware for Express comes from the Connect framework and as of Jul 2011 Connect no longer includes compiler. So doing express.compiler(...) doesn't work anymore.
A LESS-specific middleware has been created and Express now uses that if you include it in your startup config. express -c less will add this line to the config:
app.use(require('less-middleware')({ src: __dirname + '/public' }));
If you have an older version of Express and Connect, you can add less-middleware to your package.json and add the line above to get it working.
It works pretty much the same as the original compiler, but includes some more bells and whistles.
less-middleware project repository
Thanks to Hector i resolved the issue. I had the wrong version of express installed and changing express to = 2.5.0 from >=2.5.0 and reinstalling dependencies has fixed the issue and i am now able to run the app. Thanks