mongoose setCurrentLogger does not work - node.js

I'm trying to change the mongoose console log printing using the setCurrentLogger function as described here and in the tutorial for older mongo driver here. I didn't find any instructions to do that with mongoose only with the native mongodb driver.
In order to test it, I just tried changing only the printed msg:
var mongoose = require('mongoose');
var MongoLogger = require('mongodb').Logger;
var MongooseLogger = mongoose.mongo.Logger;
MongoLogger.setCurrentLogger(function(msg, context) {
console.log('aaaaaa', context);
});
MongooseLogger.setCurrentLogger(function(msg, context) {
console.log('aaaaaa', context);
});
But it doesn't seems to work, I'm still getting the full error stack priting on console, instead of the expected aaaaaa.
The question is, how to change the logger function in mongoose like the setCurrentLogger function described for the native driver

I noticed it doesn't work unless you set the logger after connecting. And you need to set the log level too:
const Mongoose = require('mongoose');
const Logger = Mongoose.mongo.Logger;
Mongoose.connect(uri);
Logger.setLevel('debug');
Logger.setCurrentLogger(function(message, context) {
console.log(message);
});

Related

How to work with NumberLong() with nodejs mongo driver

I need to insert data into my mongoDB, like such:
db.collection('Test').insert({
"Name" : "Some",
"UserID" : NumberLong(2147483647),
...
Inserts should happen from a nodejs script that interacts with mongo db
All is well, except for the NumberLong().
I'm getting the following error:
ReferenceError: NumberLong is not defined
at /root/MongoPolluter/MongoPolluter.js:107:23
at connectCallback (/root/MongoPolluter/node_modules/mongodb/lib/mongo_client.js:505:5)
at /root/MongoPolluter/node_modules/mongodb/lib/mongo_client.js:443:13
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
What I have tried:
adding var BSON = require('bson'); after installing it. Maybe I should use BSONElements?
Read this: MongoDB differences between NumberLong and simple Integer? - from which I go the notion that I could use the NumberLong only from mongo shell? Not sure if that is correct.
Also read about this: var Long = require('mongodb').Long; - should I just replace NumbreLong() w/ Long.fromString('')? Is there no way of getting the NumberLong() to work?
Thanks
NumberLong is using for mongo shell only. If you use in nodejs (javascript) it no mean.
I use mongoose and only Number type of data
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var MyNumber = mongoose.model('my_number', { long_number: Number });
var record = new MyNumber({ long_number: 1234556 });
record.save(function (err) {
if (err) {
console.log(err);
} else {
console.log('ok');
}
});
// have to defind ObjectId when use even it a default type data of mongodb
var id = mongoose.Types.ObjectId('4edd40c86762e0fb12000003');

Cannot overwrite `Kitten` model once compiled

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();

Will mongoose support initializeOrderedBulkOp() which is a new feature in Mongo DB - 2.6

Am using mongoose - 3.8.8 to connect to Mongo DB. I tried out initializeOrderedBulkOp() - a new feature of MongoDB - 2.6 in mongo Shell and i got proper output. But am not able to do the same with mongoose.
Here is a sample code
var mongoose = require('mongoose');
var conn = mongoose.createConnection('mongodb://localhost:27017/testDB');
conn.on('error', function callback (err,data) {
console.log('Error in connecting to DB');
});
var Schema = mongoose.Schema,
schema = new Schema({id:Number},{strict:false}),
modelObj = conn.model('', schema, 'documents');
var query = modelObj.initializeOrderedBulkOp();
Am getting error like
"modelObj has no method 'initializeOrderedBulkOp"
Any suggestions on this ???
You're really close. You need to drop down a level to the native driver. You can do that like so:
var query = modelObj.collection.initializeOrderedBulkOp();
From there you can do things like:
// queue a doc to be inserted
query.insert({ name: 'Some Name' })
// ... more inserts ...
// execute the bulk operation
query.execute(next)
One thing to note though, the un-ordered equivalent, initializeUnOrderedBulkOp(), does not seem to exist in version 3.8.9.

Mongoose Trying to open unclosed connection

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

Method not found Error

I am new to node.js and mongo db. What I am trying to do is to call the ordered function in my model.js from index.js but I have a complain
object function model() has no method ordered()
routes/index.js
var pics_ = models.Picture.ordered();
model.js
Picture.prototype.ordered = function() {
var ordered = mongoose.Picture.find().sort({points:-1}).toArray()
console.log(ordered);
return ordered;
};
If you want to add methods to your models, you should use the Mongoose supported ways for doing that. See http://mongoosejs.com/docs/methods-statics.html

Resources