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 in adding entries to the database but I have problems retrieving them. I am a bit confused about how the whole thing works. My understanding is the following:
There are the schemas, which are like classes in oop, so just a blueprint for a record in the database. The model is a record, OK, maybe a bit more, since I saw that you can add a method to the model. Well... I don't really understand how to use them. Can you give me a clue what really are they?
Back to the subject: When issuing the find command, it calls the anonymous function and docs should be the result right? Now how do I access them? Since now if I log the 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 trough the docs? Or how do I retrieve my records?
See Question&Answers more detail:
os