mongodb - node.js + express + mongo的编写模式疑问

【字号: 日期:2022-10-06浏览:24作者:雯心

问题描述

最近在学习node.js, 顺便想使用node.js+express+mongo弄一个系统, 用来学习前端的知识. 在选用数据库时候使用mongo. 于是我编写了一下如下代码:

/* * 学生管理功能模块 * 文档参考: doc/dbtables/student.md * 支持的操作为: 新增, 编辑, 修改, 批量删除 */var express = require(’express’);var router = express.Router();var init = function(callback) { var MongoClient = require(’mongodb’).MongoClient; var url = ’mongodb://localhost:27017/test_system’; MongoClient.connect(url, function (err, db) {assert.equal(null, err);console.log('Connected successfully to server');var collection = db.collection(’students’);callback(collection); });};var cal = function(collection) { router.get(’/’, function(req, res, next) {collection.find({}).toArray(function(err, students) { if (!err) {console.log(students);res.render(’students’, {students: students}); }}); });};init(cal);

不太熟悉node.js + express的开发模式, 我这里使用数据库查询时候, 必须先连接成功数据库, 然后使用回调调用正常的POST/GET的方法. 这样很不是灵活.

有没有更好的解决方法, 例如数据库的访问不是异步式的.

问题:

node.js + express + mongo中, 在实际项目中使用它们的人, 能否大概讲述下如何进行模块的编写?

问题解答

回答1:

有一个不错的解决方案是数据库操作的功能用后端Java或者PHP等写成REST接口,例如https://api.myapp.com/v1.0/class/student_id,然后在Node直接调用这个接口。

相关文章: