I am making an app using nodejs and I am learning the mongodb, but I do it just like the docs. but the command prompt shows:
events.js:141
throw er; // Unhandled 'error' event
^
Error: Trying to open unclosed connection.
at NativeConnection.Connection.open (C:\Users\html5col\Desktop\express\node_modules\mongoose\lib\connection.js:236:15)
at Mongoose.connect (C:\Users\html5col\Desktop\express\node_modules\mongoose\lib\index.js:241:47)
at Object.<anonymous> (C:\Users\html5col\Desktop\express\app.js:19:10)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3
//my app.js file
var url = 'mongodb://fran84:fran@ds013250.mlab.com:13250/ndeme';
//ABOVE URL USING MLAB SERVICE
var mongoose = require('mongoose');
mongoose.connect(url);
console.log('isonerror');
var mydb = mongoose.connection;
console.log('ismydb');
mydb.on('error', console.error.bind(console, 'connection error:'));
mydb.once('open', function() {
// we're connected!
console.log('Connected to MongoDB');
var Schema = mongoose.Schema,
objectId = Schema.objectId;
var postSchema = mongoose.Schema({//With Mongoose, everything is derived from a Schema.
//id: objectId,//对象id
name: {type: String,default:20},
gender: {type: String,default:'male'},
// created_at: Date
}, { timestamps });
//add "speak" functionality to our documents:
postSchema.methods.speak = function(){
var greeting = this.name
? "His name is " + this.name
: "I do not have a nanme";
console.log(greeting);
}
//The next step is compiling our schema into a Model
var myModel = mongoose.model('try',postSchema);
var instance = new myModel({name:'roger',gender:'female'});
console.log(instance.name,instance.gender);
instance.save(function(err,instance){
if(err){
return console.error(err);
}
instance.speak();
});
//access all of the kitten documents through our myModel model.
myModel.find(function(err,tries){
if(err){return console.error(err)}
console.log(tries);
});
});
MORE: ACCORDING DOCS:http://mongoosejs.com/docs/index.html
ADD 2: It seems that when I deletes the content of the mydb.once's callback function, it still shows the same problem.