gpt4 book ai didi

javascript - nodejs查询数据和代码组织

转载 作者:行者123 更新时间:2023-11-30 17:51:39 25 4
gpt4 key购买 nike

刚开始学习 nodejs,对 js 也很陌生,四处寻找最佳实践并遇到了这个: https://stackoverflow.com/a/15572522/1203349

我正在开发一个使用这种结构的应用程序。他建议将数据库调用放在相应的 model/model.js 文件中。
例如。
使用他的示例,假设我想要一个完整的博客列表。
routes/blog/index.js 中,我应该做类似的事情吗:

var Model = require('../../models');
module.exports = function(app){
app.get('/blog', function(req,res){
//what now? function calls into Model? how?
//also, why doesn't Model.blogModel.find({}, function(err, blogs){
//work with blogs
//}; work? I'm getting a ReferenceError: blogModel is not defined.
});
}

models/blog.js 中,

....
exports.<every function for crud>?

示例实现将不胜感激。

最佳答案

Amol 的回答很好,应该可以帮助您入门,但听起来您在模块方面的代码组织方面也遇到了问题。

对于您项目中的本地模块,假设您有一个名为 models.js 的文件,它看起来像:

// models.js
function Customer () {
// some properties
}

function Invoice () {
// some properties
}

module.exports = {
Customer: Customer,
Invoice: Invoice
}

然后在您的主应用程序中,您将像这样访问您的模型:

// app.js
var models = require('./models')
myCustomer = new models.Customer();
myInvoice = new models.Invoice();

希望对你有帮助,
亚伦

关于javascript - nodejs查询数据和代码组织,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18886129/

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