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']]);
}
route / 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;
이 코드에 대해 몇 가지 질문이 있습니다.
a) 콜백 함수를 Category.find (callback)의 models / category.js에 전달할 때 route / categories.js에서 콜백 메커니즘이 어떻게 작동합니까? 우리가 Category.find ()의 일부가되는 전체 res.render를 수행하고 있기 때문에 그것은 나에게 이상해 보입니다.
b) 제한은 어디에 지정됩니까?
c) 왜 카테고리 앞에 var가 없는지 = require ( '../ models / category.js');
a) 실제로 일어나는 일이며 좋은 일 입니다. 데이터베이스 res.render
에서 find()
작업이 실행되고 결과가 다시 전송되어 몽구스 코드가 반환 될 때까지 호출되지 않습니다 . 쿼리 결과를 얻은 후에 콜백 함수를 실행하고 싶으 므로 res.render
이전 호출 은 훨씬 더 기괴 할 것입니다.
b) 문서에서. http://mongoosejs.com/docs/api.html#model_Model.find이 될 수있는 쿼리 객체, 산출 동기 (쿼리가 실제로 데이터베이스에 해결하기 위해 만든 전에 예)를 추가로 지정 where
, limit
등
c) 누군가가 게으 르기 때문에. 이 예에서는 실제로 때문에없이 변화를하지 않는 var
(또는 const
또는 let
현대 JS에서) 변수 선언이 파일의 로컬 컨텍스트에 압정으로 고정되는 routes/categories.js
모듈의 컨텍스트 및 때문에이 Categories
그 범위의 상단에 선언, var
변수가 바인딩되는 위치를 변경하지 않습니다. 그러나 게으른, 그리고 좋은 예 코드, 즉 한다 이 var
그것의 앞에.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다