gpt4 book ai didi

node.js - Node JS + MongoDB - 如何将数据从模型返回到路由?

转载 作者:可可西里 更新时间:2023-11-01 10:41:04 26 4
gpt4 key购买 nike

我刚开始使用 NodeJS + MongoDB,我有一个问题,几天来我都不知道如何解决。

我的问题是:

我有一个调用模型的路由文件,如下例所示:

路线文件:

'use strict';

module.exports = function(app) {
app.get('/api/hotels/', function(req, res) {
let hotels = new app.model.Hotels();

hotels.pageList(req.params.page, req.params.qtd, (err, docs) => {

res.status(404).json({
msg: 'implementation not found'
})

})
})
}

模型文件:

'use strict';

function Hotels() {
this._hotels = process.db.get().collection('hotels')
this._ObjectID = process.db.ObjectID()
}

Hotels.prototype.pageList = function(page, qtd, cb) {
//list all hotels
this._hotels.find(function(err, hotels) {

if (err) {
return err;
} else {
return hotels;
}
})

cb()
}

module.exports = function() {
return Hotels
}

问题是我不确定如何将模型结果返回到路由并在用户浏览器中显示 JSON 对象。

谁能帮帮我?

最佳答案

像这样尝试:

Hotels.prototype.pageList = function(page, qtd, cb) {
//list all hotels
this._hotels.find(function(err, hotels) {

cb(err, hotels);
});
}

然后,在您的 route 您可以这样做:

app.get('/api/hotels/', function(req, res) {
let hotels = new app.model.Hotels();

hotels.pageList(req.params.page, req.params.qtd, (err, hotels) => {
if(err)
res.status(404).json({
msg: 'implementation not found'
});

res.json(hotels);
})
})
}

关于node.js - Node JS + MongoDB - 如何将数据从模型返回到路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43189146/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com