import goods from '../controllers/goods'
export default function(app) {
new goods(app)
}
in goods.js, we write
import proxy from '../proxy'
class Ctrl{
constructor(app) {
Object.assign(this, {
app,
model: proxy.goods,
})
this.init()
}
......
then we register goods
routes() {
this.app.get('/api/goods/:id', this.get.bind(this))
this.app.put('/api/goods/:id', this.put.bind(this))
}
to get resource of specific ID, we pass in req.params.id
get(req, res, next) {
const params = {
query : {
_id: req.params.id
},
fields : {},
options: {},
}
const options = {
path : 'types',
select : {},
}
this.model.findOneAndPopulateAsync(params, options)
.then(doc => {
if (!doc) return res.tools.setJson(1, '资源不存在或已删除')
return res.tools.setJson(0, '调用成功', doc)
})
.catch(err => next(err))
}
this.model as defined before , is proxy.goods , so we go to find implementation of
proxy.goods.findOneAndPopulateAsync
import proxy from '../proxy'
means import proxy/index.js, there we find
import goods from '../models/goods'
and in models/goods.js we see
const Schema = mongoose.Schema({
types : [{
type: ObjectId,
ref : 'classify',
}],
name : String,
})
so that findOneAndPopulateAsync must be a method
of mongoose class, let us google it
in package.json we find mongoomise
promisify mongoose by any promise library
proxy/index.js -> import RestBase from './RestBase'
-> RestBase.js -> import FeatureBase from './FeatureBase'
-> FeatureBase.js ->import bluebird from 'bluebird'
最后终于找到findAndPopulateAsync 这个函数的实现
在
FeatureBase.js
class FeatureBase{
/**
* 关联查询资源列表
* @param {Object} params
* @param {Object} options
* @return {Function}
*/
findAndPopulateAsync(params = {}, options = {})
这里调用的params, options填充的什么数据呢?返回看 controllers/goods.js
const params = {
query : query,
fields : {},
options: opts,
}
const options = {
path : 'types',
select : {},
}
而在该函数的实现里用到了
第1个参数的各项子属性
params.options
params.query
params.fields
第2个参数options
同样在FeatureBase.js里实现了查找某个id对应资源的方法
findOneAndPopulateAsync(params = {}, options = {})
网友评论