Can't connect to mongodb from mocha test - mongodb

Connecting from the REPL works fine:
> var mongoose=require('mongoose');
undefined
> mongoose.connect('mongodb://localhost/test', function(error) {
... console.log( 'connected\n%s\n', error );
... });
returns:
{ connections:
[ { base: [Circular],
collections: {},
models: {},
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
name: 'test',
options: [Object],
_readyState: 2,
_closeCalled: false,
_hasOpened: false,
_listening: false,
_events: {},
db: [Object] } ],
plugins: [],
models: {},
modelSchemas: {},
options: {} }
> connected # Yes!
undefined
But connecting from a Mocha test suite does not work:
var mongoose = require( 'mongoose' );
console.log( 'connecting...' );
mongoose.connect( 'mongodb://localhost/test', function( error ) {
if( error) console.error( 'Error while connecting:\n%\n', error );
console.log( 'connected' );
});
returns:
$ mocha
connecting...
0 passing (0 ms)
Does anyone know why this not working?

Do you have any tests in your suite? If not it seems like mocha exits before mongoose gets a chance to connect. One of the features listed on the mocha page is
auto-exit to prevent "hanging" with an active loop
which may have something to do with it. You could try connecting to mongoose in the before method of your test suite e.g.
describe('test suite', function() {
before(function(done) {
mongoose.connect('mongodb://localhost/test', function(error) {
if (error) console.error('Error while connecting:\n%\n', error);
console.log('connected');
done(error);
});
});
});

Related

Why my mongoose request returns a query but not result data, user information in, in my case? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I don't know why it doesn't work for me now, but it did work earlier.
I need to retrieve information from my db. I can easily save data using Model.create but when I want to get data I get:
Query {
_mongooseOptions: {},
_transforms: [],
_hooks: Kareem { _pres: Map {}, _posts: Map {} },
_executionCount: 0,
mongooseCollection: NativeCollection {
collection: Collection { s: [Object] },
Promise: [Function: Promise],
opts: {
bufferCommands: true,
capped: false,
Promise: [Function: Promise],
'$wasForceClosed': undefined
},
name: 'users',
collectionName: 'users',
conn: NativeConnection {
base: [Mongoose],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
options: null,
otherDbs: [],
relatedDbs: {},
states: [Object],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
plugins: [],
_listening: false,
_connectionOptions: [Object],
client: [MongoClient],
'$initialConnection': [Promise],
_events: [Object: null prototype] {},
_eventsCount: 0,
name: 'test_name',
host: 'cocoondb-shard-00-02-qx9lu.mongodb.net',
port: 27017,
user: 'test',
pass: '1234',
db: [Db]
},
...
I have only one route and use graphql apollo server.
my express route is:
server.js (main file - enterpoint)
import confirmRoute from '../src/routes/confirm';
const app = express();
app.use('/confirm', confirmRoute);
confirm.js
import { Router } from 'express';
import SimpleCrypto from 'simple-crypto-js';
import { env } from '../../environment';
import { User } from '../models/user.model';
const secret = env.TOKEN_SECRET;
const router = Router();
router.get('/*', (req, res) => {
const crypter = new SimpleCrypto(secret);
const id = crypter.decrypt(req.url.slice(1));
const user = User.find({ id }, callback => callback);
res.status(200).send(`Hello, your email confirmed successfully : ${id}`);
})
module.exports = router;
schema
import { Schema, model } from 'mongoose';
const userSchema = new Schema({
firstname: { type: String, required: [false, 'firstname address required'] },
lastname: { type: String, required: [false, 'lastname address required'] },
email: { type: String, required: [true, 'email address required'] },
password: { type: String, required: [true, 'password required'] },
confirmed: { type: Boolean, default: false },
instagram: { type: String, default: "" },
facebook: { type: String, default: "" },
role: { type: String }
}, { timestamps: true });
export const User = model('user', userSchema, 'users');
What am I doing wrong here?
I apologise if my question is silly...
It seems you are not actually executing the query.
Please try one of this solutions to make it work.
Also I used findById, but it does not matter, you can continue to query with findOne also.
Alternative 1: then catch blocks:
router.get("/users/:id", (req, res) => {
User.findById(req.params.id)
.then(doc => {
res.send(doc);
})
.catch(err => {
console.log(err);
return res.status(500).send("something went wrong");
});
});
Alternative 2: callback
router.get("/users/:id", (req, res) => {
User.findById(req.params.id, (err, doc) => {
if (err) {
console.log(err);
return res.status(500).send("something went wrong");
}
return res.send(doc);
});
});
Alternative 3: async/await
router.get("/users/:id", async (req, res) => {
try {
let result = await User.findById(req.params.id);
res.send(result);
} catch (err) {
console.log(err);
return res.status(500).send("something went wrong");
}
});
To apply your case:
router.get("/*", (req, res) => {
const crypter = new SimpleCrypto(secret);
const id = crypter.decrypt(req.url.slice(1));
console.log("id: ", id);
User.findById(req.params.id)
.then(doc => {
console.log("doc: ", doc);
res.status(200).send(`Hello, your email confirmed successfully : ${id}`);
})
.catch(err => {
console.log(err);
return res.status(500).send("something went wrong");
});
});

grunt-protractor-runner: Unable to pick scenarios

I'm trying to create grunt tasks using grunt-protractor-runner with my protractor-cucumber framework. Below is how the Gruntfile.js looks like:
grunt.initConfig({
protractor: {
options: {
//configFile: "./config/config.js",
keepAlive: true,
noColor: false,
},
chrome: {
options: {
configFile: "./config/config.js",
args: {
autoConnect: false,
seleniumServerJar: './node_modules/webdriver-manager/selenium/selenium-server-standalone-3.141.59.jar',
chromeDriver: './node_modules/webdriver-manager/selenium/chromedriver.exe',
specs: [
'../features/calendar.feature',
'../features/deal.feature',
'../features/entitlement.feature',
'../features/filter.feature',
'../features/product.feature'
],
capabilities: {
browserName: 'chrome',
chromeOptions: {
useAutomationExtension: false,
args: ['–disable-gpu'],
}
}
}
}
}
},
});
grunt.registerTask('test', ['protractor:chrome']);
If I run command grunt test it opens the chrome browser and closes with the below log:
Running "protractor:chrome" (protractor) task
[17:22:57] I/launcher - Running 1 instances of WebDriver
[17:22:57] I/hosted - Using the selenium server at http://localhost:4444/wd/hub
0 scenarios
0 steps
0m00.000s
This doesn't pick any scenarios to run. Can you help me to understand what's the issue here? My config.conf looks like this:
const Reporter = require('../support/Reporter.js');
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
autoConnect: false,
framework: 'custom',
frameworkPath: require.resolve('protractor-cucumber-framework'),
restartBrowserBetweenTests: false,
SELENIUM_PROMISE_MANAGER: true,
ignoreUncaughtExceptions: true,
onPrepare: function () {
browser.ignoreSynchronization = false;
browser.manage().timeouts().setScriptTimeout(40 * 1000);
browser.manage().timeouts().implicitlyWait(4 * 1000);
browser.manage().window().maximize();
require('babel-register');
},
cucumberOpts: {
strict: true,
format: ['json:./reports/json/cucumber_report.json'],
require: ['../support/*.js', '../stepDefinitions/*.js', '../stepDefinitions/*.ts'],
tags: 'not #Ignore', //(#CucumberScenario or #ProtractorScenario) and (not #Ignore)
retry: 3
},
params: {
env: 'test',
test: {
url: '',
users: {
BankerRO: '',
BankerRW: '',
BusinessRiskRW: '',
RiskRW: '',
RO: '',
},
db: {
server: '',
port: '',
name: '',
userId: '',
password: '',
}
}
},
onComplete: function () {
Reporter.moveReportToArchive();
Reporter.createHTMLReport();
}
};
I finally found out the root-cause, if I keep spec[] part in the Gruntfile, grunt fails to pick the scenarios even from config.js. When I removed spec from Gruntfile and kept it in the config.js, it started working fine. I'm not sure this is how it works or a potential bug with grunt-protractor-runner
Conclusion: Looks like grunt-protractor-runner looks for specs in config.js file and ignores if you keep it in Gruntfile.js
I have raised this as an issue: https://github.com/teerapap/grunt-protractor-runner/issues/197#issue-537600108

mongoose connection error always

whenerver i try to connect mongodb using mongoose following error occurred.
{ db: { native_parser: true },
server: { poolSize: 5 },
user: '',
pass: '' }
+++++++++++++++++++++++ SERVER STARTED +++++++++++++++++++++++++++ Server running at:http://127.0.0.1:5000 DB Error jobs: { [MongoError:
auth failed] name: 'MongoError', message: 'auth failed', ok: 0,
errmsg: 'auth failed', code: 18 } var option = { db: { native_parser:
true }, server: { poolSize: 5 }, user:db.username, pass:db.password, }
mongoose.connect(option, option, function(err) {if (err) { process.exit(1); } else { console.log('MongoDB Connected', mongoUrl);
} })

mongodb mongoose connection open callback doesnt get called

I have a MEAN project and this is a snippet from my server.js
var db = require('./config/db');
// url : 'mongodb://localhost/cdnserver'
// results are same for 127.0.0.1 or the machines ip
console.log(mongoose.connect(db.url));
mongoose.set('debug', true);
mongoose.connection.on('connected', function () {
console.log('Mongoose default connection open to ' + db.url);
});
// If the connection throws an error
mongoose.connection.on('error',function (err) {
console.log('Mongoose default connection error: ' + err);
});
// When the connection is disconnected
mongoose.connection.on('disconnected', function () {
console.log('Mongoose default connection disconnected');
});
This is a setup that has been working well for over 3 months now. Now I am replicating my whole MEAN stack along with database to other machine. I took a mongodump and did mongorestore. The restored db setup looks fine through mongo from terminal.
However, when starting the server, connection-open callback is not getting called. disconnected and error callbacks are getting called if I stop the mongodb service. How do I debug this further?
I am attaching the console output from both the setups.
Setup 1 :
Mongoose {
connections:
[ NativeConnection {
base: [Circular],
collections: {},
models: {},
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
name: 'cdnserver',
options: [Object],
otherDbs: [],
_readyState: 2,
_closeCalled: false,
_hasOpened: false,
_listening: false,
db: [Object] } ],
plugins: [],
models: {},
modelSchemas: {},
options: { pluralization: true } }
Server up on 80
Mongoose default connection open to mongodb://localhost/cdnserver
1
Mongoose: videos.find({}) { skip: 0, limit: 5, fields: undefined }
Setup 2:
Mongoose {
connections:
[ NativeConnection {
base: [Circular],
collections: {},
models: {},
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
name: 'cdnserver',
options: [Object],
otherDbs: [],
_readyState: 2,
_closeCalled: false,
_hasOpened: false,
_listening: false,
db: [Object] } ],
plugins: [],
models: {},
modelSchemas: {},
options: { pluralization: true } }
Server up on 80
1
1
Mongoose default connection disconnected
Mongoose default connection error: Error: connection closed
cat /var/log/mongodb/mongodb.log shows exactly the same output in both the machines.
Update 1: The setup started working properly out of blue and it stopped again. I am not able to figure out what is making this happen.
I figured it out finally, the new setup was using a newer version of nodejs.
When I moved to 6.x from 7.x it worked fine. I guess the mongoose, node 7, mongodb versions didnt go well together.

OrientDB Server Error

I have a Problem with the orientjs Driver (https://github.com/orientechnologies/orientjs) or my OrientDB (v2.1.15). I have a Node.js Server and open a Connection to the Database Server like this:
var OrientDB = require('orientjs');
var orientserver = OrientDB({
host: 'localhost',
port: 2424,
username: 'root',
password: 'Orientdb'
});
Next I open a Database Connection and work with this DB, all works fine to this point. But if I want to list all Databases with the orientserver.list() Method I get this Error:
Unhandled rejection OrientDB.RequestError: Server user not authenticated.
at Operation.parseError (/home/mklaus/IdeaProjects/Thesis/node_modules/orientjs/lib/transport/binary/protocol28/operation.js:855:13)
at Operation.consume (/home/mklaus/IdeaProjects/Thesis/node_modules/orientjs/lib/transport/binary/protocol28/operation.js:446:35)
at Connection.process (/home/mklaus/IdeaProjects/Thesis/node_modules/orientjs/lib/transport/binary/connection.js:383:17)
at Connection.handleSocketData (/home/mklaus/IdeaProjects/Thesis/node_modules/orientjs/lib/transport/binary/connection.js:284:17)
at emitOne (events.js:90:13)
at Socket.emit (events.js:182:7)
at readableAddChunk (_stream_readable.js:147:16)
at Socket.Readable.push (_stream_readable.js:111:10)
at TCP.onread (net.js:525:20)
To find the Issue I logged my Server at this Moment and get:
Server {
useToken: false,
logger:
{ error: [Function: bound bound ],
log: [Function: bound bound ],
debug: [Function] },
transport:
BinaryTransport {
domain: null,
_events: { reset: [Function: bound ] },
_eventsCount: 1,
_maxListeners: Infinity,
connecting:
Promise {
_bitField: 268566529,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_progressHandler0: undefined,
_promise0: undefined,
_receiver0: undefined,
_settledValue: [Circular],
_boundTo: [Circular] },
closing: false,
retries: 0,
maxRetries: 5,
host: 'localhost',
port: 2424,
username: 'admin',
password: 'admin',
servers: [ [Object] ],
currentServer: 0,
enableRIDBags: true,
useToken: false,
token: <Buffer >,
sessionId: 62,
logger:
{ error: [Function: bound bound ],
log: [Function: bound bound ],
debug: [Function] },
connection:
Connection {
domain: null,
_events: [Object],
_eventsCount: 3,
_maxListeners: Infinity,
host: 'localhost',
port: 2424,
socket: [Object],
logger: [Object],
enableRIDBags: true,
closing: false,
reconnectNow: false,
protocol: [Object],
queue: [],
writes: [],
remaining: null,
connecting: false,
protocolVersion: 32 },
skipServerConnect: true },
config:
{ get: [Function: bound ],
set: [Function: bound ],
list: [Function: bound ] },
domain: null,
_events:
{ reset:
[ [Function: bound ],
[Function: bound ],
[Function: bound ],
[Function: bound ],
[Function: bound ] ],
error: [ [Object], [Object] ] },
_eventsCount: 2,
_maxListeners: Infinity }
As you can see the username and the Password is wrong. Someone know why this happen? Why I cant have Access to the Server after working with one DB on it?
*edit
Here is the Code of my nodejs Server (Not everything, just the important parts)
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var stringify = require('json-stringify-safe');
var routes = require('./routes/index');
var users = require('./routes/users');
var passport = require('passport');
var expressSession = require('express-session');
var Strategy = require('passport-local').Strategy;
var users = {};
var databases = {};
var OrientDB = require('orientjs');
var orientserver = OrientDB({
host: 'localhost',
port: 2424,
httpPort: 2480,
username: 'root',
password: 'Orientdb'
});
passport.use(new Strategy({
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true
},
function(req, username, password, cb) {
var sessID = req.sessionID;
var dbkey = username+"_"+req.params.database;
if(dbkey in databases) {
} else {
databases[dbkey] = orientserver.use({
name: req.params.database,
username: username,
password: password
});
}
users[sessID]= {id: sessID, username: username, database: dbkey};
return cb(null, users[sessID]);
}));
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(expressSession({secret: 'mySecretKey', cookie: { maxAge: 60000 }}));
app.use(passport.initialize());
app.use(passport.session());
app.get('/', function (req, res) {
});
app.get('/getAllProjects', function(req, res) {
//https://github.com/kriskowal/q
orientserver.list()
.then(function (dbs) {
var json = [];
dbs.forEach(function(value, index) {
json.push({"name": value.name});
});
//console.log('There are ' + dbs.length + ' databases on the server.');
res.status(200).send(json);
});
});
app.post('/:database',
passport.authenticate('local', { failureRedirect: '/' }),
function(req, res) {
res.redirect("/"+req.params.database);
});
So when I send the second Request to getAllProjects I get the Error.