javascript - How does this callback call work in Node.js with mongo .find call -
models/category.js
var mongoose = require('mongoose'); // category schema var categoryschema = mongoose.schema({ title: { type: string }, description: { type: string }, created_at: { type: date, default: date.now } }); var category = module.exports = mongoose.model('category', categoryschema); // categories module.exports.getcategories = function(callback, limit) { category.find(callback).limit(limit).sort([['title', 'ascending']]); }
routes/categories.js
var express = require('express'); var router = express.router(); category = require('../models/category.js'); router.get('/', function(req, res, next) { category.getcategories(function(err, categories) { if (err) res.send(err); res.render('categories', { title: 'categories', categories: categories }); }); }); router.post('/add', function(req,res) { res.send('form submitted'); }); module.exports = router;
i got few questions code
a) how callback mechanism work routes/categories.js when pass callback function models/category.js in category.find(callback). seems bizarre me since doing whole res.render becomes part of category.find() ?
b) limit specified?
c) why isn't there var in front of category = require('../models/category.js');
a) indeed happens, , good: res.render
not called until find()
operation executes on database , result sent mongoose code return you. want run callback function after result query, , calling res.render
before more bizarre.
b) in documentation. http://mongoosejs.com/docs/api.html#model_model.find yields query object, may synchronously (i.e. before query made resolve @ database) further specified where
, limit
, etc.
c) because got lazy. in example doesn't make difference because without var
(or const
or let
in modern js) variable declaration tacked onto local context, in file routes/categories.js
module context, , because categories
declared @ top of scope, var
doesn't change variable ends being bound. it's lazy, , example code, should have var
in front of it.
Comments
Post a Comment