I just started playing with mongoose and mongo. I have the following code:
var ninjaSchema = mongoose.Schema({ name: String, skill: Number }); var Ninja = mongoose.model('Ninja',ninjaSchema); module.exports = { init : function(){ console.log('Connecting to database'); mongoose.connect('mongodb://localhost/mydb'); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function callback () { console.log('Successfully connected!'); }); }, createNinja : function(name,skill){ var n = new Ninja({name:name,skill:skill}); n.save(function(err,n){ if (err) console.log('saving failed'); console.log('saved '+ n.name); }); }, getNinjas : function(){ var res = null; res = Ninja.findOne({},'name skill',function(err,docs){ if (err) console.log('error occured in the query'); return 'ninja name: '+docs.name+' ninja skill: '+docs.skill; }); return res; }
There is no problem adding records to the database, but I have problems getting them. I'm a little confused about how it all works. My understanding is this:
There are schemes that look like classes in oop, so this is just a plan for writing to the database. A model is a record, well, maybe a little more, since I saw that you can add a method to the model. Well ... I really don't understand how to use them. Can you let me know what it really is?
Back to the topic: When the find command is issued, it calls an anonymous function, and the documents should be the result correctly? Now how do I access them? Since now, if I register res, I get the following:
{ options: {}, safe: undefined, _conditions: {}, _updateArg: {}, _fields: { name: 1, skill: 1 }, _geoComparison: undefined, op: 'findOne', model: { [Function: model] base: { connections: [Object], plugins: [], models: [Object], modelSchemas: [Object], options: {} }, modelName: 'Ninja', model: [Function: model], db: { base: [Object], collections: [Object], models: {}, replica: false, hosts: null, host: 'localhost', port: 27017, user: undefined, pass: undefined, name: 'mydb', options: [Object], _readyState: 1, _closeCalled: false, _hasOpened: true, _listening: true, _events: [Object], db: [Object] }, schema: { paths: [Object], subpaths: {}, virtuals: [Object], nested: {}, inherits: {}, callQueue: [], _indexes: [], methods: {}, statics: {}, tree: [Object], _requiredpaths: [], options: [Object], _events: {} }, options: undefined, collection: { collection: [Object], opts: [Object], name: 'ninjas', conn: [Object], queue: [], buffer: false } } }
Also, if I use Ninja.find(...,function(err,docs){ ... }) , how do I go through the docs? Or how to get my notes?