Currently the only thing I have in my file is the following:
var mongo = require('mongodb').MongoClient,
url = 'mongodb://localhost:27017/learnyoumongo';
console.log(mongo);
When I run the verify command, I get the following error:
/usr/local/lib/node_modules/learnyoumongo/exercises/find/exercise.js:37
db.collection('parrots').remove({}, function(err) {
^
TypeError: Cannot read property 'collection' of undefined
at Exercise.<anonymous> (/usr/local/lib/node_modules/learnyoumongo/exercises/find/exercise.js:37:5)
at next (/usr/local/lib/node_modules/learnyoumongo/node_modules/workshopper-exercise/exercise.js:260:17)
at Exercise.end (/usr/local/lib/node_modules/learnyoumongo/node_modules/workshopper-exercise/exercise.js:266:5)
at Workshopper.end (/usr/local/lib/node_modules/learnyoumongo/node_modules/workshopper/workshopper.js:191:12)
at Workshopper.done (/usr/local/lib/node_modules/learnyoumongo/node_modules/workshopper/workshopper.js:323:19)
at Exercise.<anonymous> (/usr/local/lib/node_modules/learnyoumongo/node_modules/workshopper-exercise/exercise.js:149:14)
at /usr/local/lib/node_modules/learnyoumongo/node_modules/workshopper-exercise/exercise.js:136:16
at Exercise.<anonymous> (/usr/local/lib/node_modules/learnyoumongo/node_modules/workshopper-exercise/filecheck.js:10:14)
at FSReqWrap.oncomplete (fs.js:95:15)
When I took a look at the exercises.js file, I see the error is pointing to the .addCleanup function and the db it is trying to close is undefined.
This seems like a connection/configuration error, but I passed the first two modules. Can anyone help?
Update
This is definitely a connection error. The previous scenario was created using the command in the workshop module mongod --port 27017 --dbpath=./data, however when I opened a new terminal tab and just ran mongo without any arguments, the verify command actually output the "Actual/Expected" evaluation and module results.
To the user who asked for the rest of the script, please understand if you are unfamiliar with nodeschool that this is an entire repository with module based automated/interactive tutorials, so this is not all of the code. In any case, here is what you requested:
var mongo = require('mongodb').MongoClient
, exercise = require('workshopper-exercise')()
, filecheck = require('workshopper-exercise/filecheck')
, execute = require('workshopper-exercise/execute')
, comparestdout = require('workshopper-exercise/comparestdout')
exercise = filecheck(exercise)
exercise = execute(exercise)
exercise = comparestdout(exercise)
var db, url = 'mongodb://localhost:27017/learnyoumongo'
exercise.addSetup(function(mode, cb) {
var self = this
this.submissionArgs = [3]
this.solutionArgs = [3]
mongo.connect(url, function(err, _db) {
if (err) return cb(err)
db = _db
col = db.collection('parrots')
col.insert([{
name: 'Fred'
, age: 1
}, {
name: 'Jane'
, age: 3
}, {
name: 'Jenny'
, age: 10
}], cb)
})
})
exercise.addCleanup(function(mode, pass, cb) {
db.collection('parrots').remove({}, function(err) {
if (err) return cb(err)
db.close()
cb()
})
})
module.exports = exercise
I think that should be:
var mongo = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/learnyoumongo', function(err, db) {
console.log(err);
});
There was definitely a connection problem. I'm not sure exactly where the bug was, but I reloaded learnyoumongo and reinstalled a couple of node packages. When I did that I had to go back and change permissions on the data directory again.
My recommendation if anyone else faces strange config errors, is to try to reinstall. Then when you connect, it doesn't hurt to re-verify the CONNECT module to make sure you have a good connection when you start your work space.
Related
I have tried this code :
const invNum = require('invoice-number');
router.post('/checkout', async (req, res, next) => {
if (!req.session.cart) {
return res.redirect('/pos/');
}
var saleList = Sale.find().sort({ _id: -1 }).limit(1); // removed (err, data)=>{} to simply view it is working tested already
var settings = await Setting.find({}); // removed try and catch to simply view it is working tested already
var ticketNumber;
ticketNumber = !saleList ? invNum.next('0000000') : invNum.next(saleList.ticket_number);
var sale = new Sale({
ticket_number:ticketNumber,
cart: req.session.cart,
created_at: new Date()
});
sale.save((err, product) => {
createReceipt(settings, req.session.cart, "receipts/"+ticketNumber+".pdf");
req.session.cart = null;
res.redirect('/pos/');
});
});
I got this error:
TypeError: invNum.next is not a function
The problem is with invNum.next().
invNum.next() is a Node.js module to generate invoice number sequentially installed from npm.
Example:
invNum.next('2017/08/ABC001')
// => 2017/08/ABC002
I have tried already suggestions from previous stackoverflow posts by trying Promises or await async function in order to get this code to work. Hopefully, you can help or suggest something. Thank you.
There is a problem in version of invoice-number module. In the npm it is showing as 1.0.6 but in the GitHub repository it has 1.0.5 in the package.json file.
https://github.com/amindia/invoice-number.
I have tested this module by taking from Github repository and it's working fine.
Please take the source of this module from the given link it will works fine.
Seems to be some error in the module. I tried the below code snippet on RunKit
https://runkit.com/embed/ws2lv1y38mt4
var invNum = require('invoice-number')
try{
invNum.next('sdfsd1')
} catch(e){
console.log(e)
}
Getting the same error
I got this error:
TypeError: invNum.next is not a function UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()
What is the output when you use the console.log on invNum?
Also use try catch and inside call invNum.next with await. Maybe something inside this function is throwing an error.
Edit: as jfriend00 says, if an plain text (like your "0000...") is working, probably the saleList is returning some error and you are not catching or treating the error.
Edit2: The last update on this NPM code is from 1 year ago and fewer people used this lib, probably is broken.
There is some part of the code from the index.js of the lib:
function _next (invoiceNumber) {
if (!invoiceNumber)
throw new Error('invoiceNumber cannot be empty')
var array = invoiceNumber.split(/[_/:\-;\\]+/)
var lastSegment = array.pop()
var priorSegment = invoiceNumber.substr(0, invoiceNumber.indexOf(lastSegment))
var nextNumber = alphaNumericIncrementer(lastSegment)
return priorSegment + nextNumber}
var api = { next: _next}
module.exports = api
I followed the voltdb-client-nodeJS, and implement the #AdHoc query function, but the "read" function didn't callbacked, so that can't get any queried results, can't determine if the connection is successful, too.
[callProcedure code]
var query = resultsProc.getQuery();
query.setParameters(["select * from Q_SHIPPINGCARRIERHISTORY_STREAMING where TrackingNumber=431476575751"]);
client.call(query, function read(errorCode, eventCode, results){
...
}, function write(errorCode, eventCode, results){
...
});
[connect DB code]
var config = new VoltConfiguration();
config.host = "s7biapp26";
config.port = 8080;
var client = new VoltClient([config]);
client.connect(function(code, event, results){
...
});
On the second attempt, can't require('voltjs') or require('volt') after npm install voltjs(version:voltjs#0.2.0).
So, could you provide a more detailed documentation about the voltdb-client-nodeJS, or paste a simpler demo of #AdHoc, thank you very much!
The key is connected voltdb failed by error code in connect callback function, I tried to remove the port, then connected success!
The secondly, requiring the module should require('voltjs/lib/client').
referenced the links:
https://github.com/VoltDB/voltdb-client-nodejs/issues/12
https://forum.voltdb.com/forum/voltdb-discussions/building-voltdb-applications/577-nodejs-client-for-helloworld
I've run into an issue with the Mongoose Getting Started guide.
I have MongoDB running and everything is working perfectly until I add the last line:
Kitten.find({ name: /^Fluff/ }, callback)
When I node server.js I get this error:
OverwriteModelError: Cannot overwrite Kitten model once compiled.
Here's the full error and my server.js.
Any idea what I'm doing wrong?
P.S. I'm running node 10.26, npm 1.4.13, express 4.4.3 & mongoose 3.8.12 on OS X 10.9.3.
You get the error because callback in Kitten.find({ name: /^Fluff/ }, callback) calls var Kitten = mongoose.model('Kitten', kittySchema); again. Change
Kitten.find({ name: /^Fluff/ }, callback)
to something like:
Kitten.find({ name: /^Fluff/ }, function(err, kittens) {
});
It doesn't make sense to call the callback function again.
I thought this could be useful to someone else who tries it...
I started looking into mongoose and tried Getting Started guide. I don't see the above error happening where it was reported. However, I did see it intermittently. If it happens, follow #3 below. Here are my observations:
Issue#1. If I copy paste the whole code I see an issue with "I don't have a name" as the single quote in don't is not escaped.
Solution#1. I tried to escape with \ and \\ but it didn't work. Google search didn't help. After some research I found that it is forgiving for single quotes outside the function. But, inside the function it won't work. So, I defined a variable outside the function. Probably better to define strings in a separate document for localization anyways. Above all, it works. :)
Issue#2. I see the issue at
fluffy.speak();
TypeError: fluffy.speak is not a function
Here since the first 'mongoose.model(...)' doesn't have this method, adding it later and re-running 'mongoose.model(...)' will not help.
Solution#2. Comment the first 'mongoose.model(...)'
Issue#3. When I copy paste the code from the web site, it is causing weird errors.
Solution#3. Just deleted all the tabs and empty spaces at the end of lines in a Notepad++. That took care of it.
Here is the code that worked for me (Needless to say, if it doesn't work, please copy paste first in notepad):
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection.error:'));
db.once('open', function(callback) {
//yay!
});
var kittySchema = mongoose.Schema({
name: String
});
//var Kitten = mongoose.model('Kitten', kittySchema);
//var silence = new Kitten({ name: 'Silence' });
//console.log(silence.name);
//console.log(silence);
var noname = "I don't have a name";
kittySchema.methods.speak = function () {
var greeting = this.name
? "Meow name is " + this.name
: noname;
console.log(greeting);
}
var Kitten = mongoose.model('Kitten', kittySchema);
var fluffy = new Kitten({ name : 'fluffy' });
fluffy.speak();
This is a simplified version of the problem, but basically I'm trying to open 2 mongodb connections with mongoose and it's giving me "Trying to open unclosed connection." error.
Code sample:
var db1 = require('mongoose');
db1.connect('my.db.ip.address', 'my-db');
var db2 = require('mongoose');
db2.connect('my.db.ip.address', 'my-db');
db2.connection.close();
db1.connection.close();
Any idea how to make it work?
connect() opens the default connection to the db. Since you want two different connections, use createConnection().
API link: http://mongoosejs.com/docs/api.html#index_Mongoose-createConnection
To add on Raghuveer answer :
I would also mention that instead of using mongoose directly (you are probably using it this way you end up on this post) :
require('mongoose').model(...);
You would use the returned connection :
var db = require('mongoose').connect('xxx', 'yyy');
db.model(...);
I get this issue while running my tests.
This is what I did to solve it.
//- in my app.js file.
try {
mongoose.connect('mongodb://localhost/userApi2'); //- starting a db connection
}catch(err) {
mongoose.createConnection('mongodb://localhost/userApi2'); //- starting another db connection
}
I had this problem doing unit test with mocha.
The problem came when I added a second test because beforeEach is called twice.
I've solved this with this code:
const mongoose = require('mongoose');
describe('Your test suite', () => {
beforeEach( () => {
if (mongoose.connection.db) {
return; // or done();
} else {
// connect to mongodb
});
describe('GET /some-path', () => {
it('It should...', () => {
});
});
describe('POST /some-path', () => {
it('It should...', () => {
});
});
});
Hope it helps you!
You are attempting to open the default connection ( which is not yet closed ) a 2nd time.
do the following instead
var db = require('mongoose'); //note only one 'require' needed.
var connectionToDb1 = db.createConnection('my.db1.ip.address', 'my-db1');
var connectionToDb2 = db.createConnection('my.db2.ip.address', 'my-db2');
Using mongoose.disconnect(fn):
mongoose.disconnect(() => {
// here it would be possible "reset" models to fix
// OverwriteModelError errors
mongoose.models = {};
// here comes your logic like registering Hapi plugins
server.register(somePlugin, callback);
});
I found this question typing the error message and despite my problem is a bit different I believe it could be useful for those using Hapi. More specifically Hapi + rest-hapi + mocha.
When running mocha with --watch option I was facing both: OverwriteModelError and Error: Trying to open unclosed connection errors.
Simple Solution -
Use mongoose.createConnection() instead of mongoose.connect()
Its occurs because of version issue
I have a Locations model and a Recorders model. I want to be able to pass all of the data for both data sets to my view model. How can I access them though because I think they're not in scope since I'm getting undefined errors because I'm calling 'all'
https://gist.github.com/3998302
var Main = function () {
this.index = function (req, resp, params) {
var self = this;
var data = {};
geddy.model.Locations.all(function(err, locations) {
data.locations = locations;
geddy.model.Recorders.all(function(err, recorders) {
data.recorders = recorders;
self.respond({params: params, data: data}, {
format: 'html'
, template: 'app/views/locations/index'
}
});
}););
};
};
exports.Main = Main;
Error snippet:
timers.js:103
if (!process.listeners('uncaughtException').length) throw e;
^
TypeError: Cannot call method 'all' of undefined
at index (G:\code\PeopleTracker\app\controllers\main.js:23:24)
at controller.BaseController._handleAction.callback (C:\Users\Chris\AppData\Roaming\npm\node_modules\geddy\lib\base_
controller.js:387:22)
So it looks like you're initializing the data variable to 'undefined'. Try data = {} instead. If that doesn't fix it, I'll do some troubleshooting with you.
EDIT
If that doesn't do it for you, try installing geddy again:
npm uninstall -g geddy && npm install -g geddy
If that doesn't do it, make sure that your DB is actually running, make sure that the models are defined (try geddy console to check your models), and make sure that you're on the latest stable version of node.
Very late to the party, but I believe you can just call
geddy.model.Locations.all(function(err, locations) {
geddy.model.Recorders.all(function(err, recorders) {
var data = {};
data.locations = locations;
data.recorders = recorders;
self.respond({params: params, data: data}, {
format: 'html'
, template: 'app/views/locations/index'
}
});
}););
You could also have the respond say
self.respond({params: params, locations: locations, recorders: recorders});
but if you want all of that data available from the data literal you need it defined in the lowest scope callback. The callbacks can read above their scope but they cannot write above it.