简体   繁体   中英

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

// Get 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 a few questions about this code

a) how does the callback mechanism work from routes/categories.js when we pass that callback function to models/category.js in Category.find(callback). That seems bizarre to me since we are doing a whole res.render which becomes part of Category.find() ?

b) Where is limit specified?

c) Why isn't there var in front of Category = require('../models/category.js');

a) that is indeed what happens, and is good: res.render will not get called until the find() operation executes on the database and a result is sent back for the mongoose code to return to you. You want to run the callback function after you get the result for your query, and so calling res.render before would be much more bizarre.

b) in the documentation. http://mongoosejs.com/docs/api.html#model_Model.find yields a Query object, which may be synchronously (ie before the query is actually made to resolve at the database) further specified with where , limit , etc.

c) because someone got lazy. In this example it doesn't actually make a difference because without var (or const or let in modern JS) a variable declaration is tacked onto the local context, which in your file is the routes/categories.js module context, and because Categories is declared at the top of that scope, var doesn't change where the variable ends up being bound. But it's lazy, and for good example code, that should have var in front of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM