当前位置: 首页 > news >正文

住房和建设建设局网站惠州外贸网站建设

住房和建设建设局网站,惠州外贸网站建设,网站建设 東道网络,asp网站开发的开发环境Node Express 后台开发 —— 起步 前面陆续学习了一下 node、npm、模块#xff0c;也稍尝试 Express#xff0c;感觉得换一个思路加快进行。 比如笔者对前端的开发已较熟悉#xff0c;如果领导给一个内部小网站的需求#xff0c;难道说你得给我配置一个后端#xff1f;…Node Express 后台开发 —— 起步 前面陆续学习了一下 node、npm、模块也稍尝试 Express感觉得换一个思路加快进行。 比如笔者对前端的开发已较熟悉如果领导给一个内部小网站的需求难道说你得给我配置一个后端 又不是做一个复杂的后端只是简单的数据存储增删改查、上传文件、下载csv或excel无需考虑性能、稳定性、负载均衡等等怎么就不能做 目标 实现简单后台的开发和部署 Express 项目生成器 生成项目 可通过应用生成器工具 express-generator 可以快速创建一个应用的骨架 创建项目文件夹 spug-back-end进入项目后执行 npx express-generator: Administrator /e/spug-back-end $ npx express-generator npm WARN exec The following package was not found and will be installed: express-generator4.16.1 npm WARN deprecated mkdirp0.5.1: Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.)warning: the default view engine will not be jade in future releaseswarning: use --viewjade or --help for additional optionscreate : public\create : public\javascripts\create : public\images\create : public\stylesheets\create : public\stylesheets\style.csscreate : routes\create : routes\index.jscreate : routes\users.jscreate : views\create : views\error.jadecreate : views\index.jadecreate : views\layout.jadecreate : app.jscreate : package.jsoncreate : bin\create : bin\wwwinstall dependencies:$ npm installrun the app:$ DEBUGspug-back-end:* npm start生成如下内容 Administrator /e/spug-back-end $ ll total 5 -rw-r--r-- 1 Administrator 197121 1075 Apr 14 15:06 app.js drwxr-xr-x 1 Administrator 197121 0 Apr 14 15:06 bin/ -rw-r--r-- 1 Administrator 197121 301 Apr 14 15:06 package.json drwxr-xr-x 1 Administrator 197121 0 Apr 14 15:06 public/ drwxr-xr-x 1 Administrator 197121 0 Apr 14 15:06 routes/ drwxr-xr-x 1 Administrator 197121 0 Apr 14 15:06 views/Tip: 对于较老的 Node 版本8.2.0 以下请通过 npm 将 Express 应用程序生成器安装到全局环境中并使用 $ npm install -g express-generator $ express根据上文提示安装依赖 npm install Administrator /e/spug-back-end $ npm install npm WARN deprecated constantinople3.0.2: Please update to at least constantinople 3.1.1 npm WARN deprecated transformers2.1.0: Deprecated, use jstransformer npm WARN deprecated jade1.11.0: Jade has been renamed to pug, please install the latest version of pug instead of jadeadded 99 packages, and audited 100 packages in 22s1 package is looking for fundingrun npm fund for details8 vulnerabilities (1 low, 4 high, 3 critical)To address all issues (including breaking changes), run:npm audit fix --forceRun npm audit for details.全局安装 nodemon在Node.js应用程序开发过程中使用的简单监视器脚本编码过程中无需重启 node 服务即可生效 PS E:\spug-back-end npm i -g nodemonchanged 32 packages, and audited 33 packages in 1s3 packages are looking for fundingrun npm fund for detailsfound 0 vulnerabilities修改启动脚本 version: 0.0.0,private: true,scripts: { - start: node ./bin/wwwstart: nodemon ./bin/www通过 npm run start 本地启动服务 PS E:\spug-back-end npm run start spug-back-end0.0.0 startnodemon ./bin/www[nodemon] 2.0.22 [nodemon] to restart at any time, enter rs [nodemon] watching path(s): *.* [nodemon] watching extensions: js,mjs,json [nodemon] starting node ./bin/www入口文件 /bin/www.js 默认使用的是 3000 端口var port normalizePort(process.env.PORT || 3000); 浏览器访问 http://localhost:3000/页面显示 Express Welcome to Express项目解读 模板 views 目录中存放的是 jade 模板文件 Administrator /e/spug-back-end/views (master) $ ls error.jade index.jade layout.jade首页对应的模板是 index.jade: Administrator /e/spug-back-end/views (master) $ cat index.jade extends layoutblock contenth1 titlep Welcome to #{title}Express 生成器默认使用 jade 模板对前端不是很友好笔者通过 npx express-generator --viewejs 选用 ejs模板对前端更友好重新创建。 首页对应模板 index.ejs !DOCTYPE html htmlheadtitle% title %/titlelink relstylesheet href/stylesheets/style.css //headbodyh1% title %/h1pWelcome to % title %/p/body /html入口文件 bin/www.js 是应用的入口文件。 核心代码如下 // 加载 app.js var app require(../app); var http require(http);var port normalizePort(process.env.PORT || 3000); app.set(port, port);// 创建 http server var server http.createServer(app); server.listen(port);完整代码如下 #!/usr/bin/env node/*** Module dependencies.*/var app require(../app); var debug require(debug)(spug-back-end:server); var http require(http);/*** Get port from environment and store in Express.*/var port normalizePort(process.env.PORT || 3000); app.set(port, port);/*** Create HTTP server.*/var server http.createServer(app);/*** Listen on provided port, on all network interfaces.*/server.listen(port); server.on(error, onError); server.on(listening, onListening);/*** Normalize a port into a number, string, or false.*/function normalizePort(val) {var port parseInt(val, 10);if (isNaN(port)) {// named pipereturn val;}if (port 0) {// port numberreturn port;}return false; }/*** Event listener for HTTP server error event.*/function onError(error) {if (error.syscall ! listen) {throw error;}var bind typeof port string? Pipe port: Port port;// handle specific listen errors with friendly messagesswitch (error.code) {case EACCES:console.error(bind requires elevated privileges);process.exit(1);break;case EADDRINUSE:console.error(bind is already in use);process.exit(1);break;default:throw error;} }/*** Event listener for HTTP server listening event.*/function onListening() {var addr server.address();var bind typeof addr string? pipe addr: port addr.port;debug(Listening on bind); }Tip: 和我们之前创建的最简单的服务器类似 app.js 入口文件中引入 app.js完整代码如下 var createError require(http-errors); var express require(express); var path require(path); var cookieParser require(cookie-parser); var logger require(morgan);var indexRouter require(./routes/index); var usersRouter require(./routes/users); // Creates an Express application var app express();// view engine setup // 模板引擎相关代码 app.set(views, path.join(__dirname, views)); app.set(view engine, ejs);app.use(logger(dev)); // for parsing application/json app.use(express.json()); // for parsing application/x-www-form-urlencoded app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); // 放开静态资源 app.use(express.static(path.join(__dirname, public)));// 定义两个路由。一个返回页面一个返回后端数据 // app.use([path,] callback [, callback...]) - 在指定路径挂载指定的一个或多个中间件函数当请求路径的基匹配路径时执行中间件函数。 app.use(/, indexRouter); app.use(/users, usersRouter);// catch 404 and forward to error handler app.use(function(req, res, next) {next(createError(404)); });// error handler app.use(function(err, req, res, next) {// set locals, only providing error in developmentres.locals.message err.message;res.locals.error req.app.get(env) development ? err : {};// render the error pageres.status(err.status || 500);res.render(error); });module.exports app;和我们之前用 Express 实现的报名系统 非常类似。这里创建了一个 Express 应用并定义了两个示例路由: var indexRouter require(./routes/index); var usersRouter require(./routes/users);// 返回页面 app.use(/, indexRouter); // 返回后端数据 app.use(/users, usersRouter);路由 app.js 使用了两个路由。内容如下 // routes/index.js var express require(express); var router express.Router();/* GET home page. */ router.get(/, function(req, res, next) {res.render(index, { title: Express }); });module.exports router;// routes/users.js var express require(express); var router express.Router();/* GET users listing. */ router.get(/, function(req, res, next) {res.send(respond with a resource); });module.exports router;浏览器访问 http://localhost:3000/users页面显示 respond with a resource。 mongodb 数据库通常会安装到 linux 中这里以 ubuntu 为例通过 apt-get install mongodb 即可安装非常方便 // 笔者刚已执行 rootlinux:/home/pjl# apt-get install mongodb Reading package lists... Done Building dependency tree Reading state information... Done mongodb is already the newest version (1:3.6.9really3.6.890~g8e540c0b6d-0ubuntu5.3). 0 upgraded, 0 newly installed, 0 to remove and 150 not upgraded.数据库现在已经启动我们通过mongo -version验证安装成功 rootlinux:/home/pjl# mongo -version MongoDB shell version v3.6.8 git version: 8e540c0b6db93ce994cc548f000900bdc740f80a OpenSSL version: OpenSSL 1.1.1f 31 Mar 2020 allocator: tcmalloc modules: none build environment:distarch: x86_64target_arch: x86_64mongodb 配置文件是 /etc/mongodb.conf。请注意下面两项配置 // 远程连接 #bind_ip 127.0.0.1 bind_ip 0.0.0.0// 开机自启动 #auth true auth trueMongoDB shell 输入 mongo 即可进入 MongoDB shell操作mongo rootlinux:/home/pjl# mongo MongoDB shell version v3.6.8 connecting to: mongodb://127.0.0.1:27017 Implicit session: session { id : UUID(aedc6541-4a67-4e60-8eb4-d1325c82d061) } MongoDB server version: 3.6.8 Welcome to the MongoDB shell. For interactive help, type help. For more comprehensive documentation, seehttp://docs.mongodb.org/ Questions? Try the support grouphttp://groups.google.com/group/mongodb-user Server has startup warnings: 2023-04-15T14:34:32.3270800 I STORAGE [initandlisten] 2023-04-15T14:34:32.3270800 I STORAGE [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine 2023-04-15T14:34:32.3270800 I STORAGE [initandlisten] ** See http://dochub.mongodb.org/core/prodnotes-filesystem 2023-04-15T14:34:34.8610800 I CONTROL [initandlisten] 2023-04-15T14:34:34.8610800 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database. 2023-04-15T14:34:34.8610800 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted. 2023-04-15T14:34:34.8610800 I CONTROL [initandlisten]helpdb.help() help on db methodsdb.mycoll.help() help on collection methodssh.help() sharding helpersrs.help() replica set helpershelp admin administrative helphelp connect connecting to a db helphelp keys key shortcutshelp misc misc things to knowhelp mr mapreduceshow dbs show database namesshow collections show collections in current databaseshow users show users in current databaseshow profile show most recent system.profile entries with time 1msshow logs show the accessible logger namesshow log [name] prints out the last segment of log in memory, global is defaultuse db_name set current databasedb.foo.find() list objects in collection foodb.foo.find( { a : 1 } ) list objects in foo where a 1it result of the last line evaluated; use to further iterateDBQuery.shellBatchSize x set default number of items to display on shellexit quit the mongo shellshow dbs admin 0.000GB config 0.000GB local 0.000GB通过 help 可以查看帮助通过show dbs 发现现在有三个数据库。 新建数据库 通过 use 可以创建或切换数据库。比如 // use - 创建数据库 pjl_db。如果存在则直接切换use pjl_db switched to db pjl_db // db - 目前操作的是 pjl_db 数据库db pjl_db由于新建的数据库 pjl_db 什么都没有所以通过 show dbs 显示不出来可通过 createCollection 创建表再次查询即可显示该数据库。比如 // 新建数据库未能展示show dbs admin 0.000GB config 0.000GB local 0.000GB // 通过 tab 建有提示db.create db.createCollection( db.createRole( db.createUser( db.createView( // 创建表 users。这里叫集合db.createCollection(users) { ok : 1 } // 再次查询则可显示新建数据库 pjl_dbshow dbs admin 0.000GB config 0.000GB local 0.000GB pjl_db 0.000GBTipdb.createCollection(pjl_db, {size: 1024*1024, capped: true, max: 1000}) - 创建 pjl_db 数据库同时这个数据库最多 1M记录数只能有1000条在多一条则把第一条给替代。db.createCollection(users) 则不作限制。 删除数据库 通过 db.dropDatabase() 即可删除数据库。比如 db.dropDatabase() { dropped : pjl_db, ok : 1 }show dbs admin 0.000GB config 0.000GB local 0.000GB新增、查看和删除表 通过 db.createCollection(users) 新建 users 表。比如 // 创建表 users。这里叫集合db.createCollection(users) { ok : 1 } // 再次查询则可显示新建数据库 pjl_dbshow dbs admin 0.000GB config 0.000GB local 0.000GB pjl_db 0.000GBdb.getCollectionNames - 查看有哪些表db.tableName.drop - 删除某张表 示例 // 新建两张表: table-b、table-cdb.createCollection(table-b) { ok : 1 }db.createCollection(table-c) { ok : 1 } // tab 提示db.getCollection db.getCollection( db.getCollectionInfos( db.getCollectionNames( // 有哪些表db.getCollectionNames() [ table-b, table-c, users ] // 删除table-b表失败db.table-b.drop() 2023-04-15T15:17:10.2320800 E QUERY [thread1] ReferenceError: b is not defined : (shell):1:1 // 删除table-b表成功db[table-b].drop() truedb.getCollectionNames() [ table-c, users ]表格-新增数据 通过 db.users.save 可以向 users 表中单条、批量插入数据。甚至字段名不同字段数量不同也能插入。请看示例 // 给 users 表插入一条数据 {name: pjl, age: 18}db.users.save({name: pjl, age: 18}) WriteResult({ nInserted : 1 }) // 查询users表db.users.find() { _id : ObjectId(643a513d73f16a13ae248f42), name : pjl, age : 18 } // 批量插入数据db.users.save([{name: pjl2, age: 19}, {name: pjl3, age: 20}]) BulkWriteResult({writeErrors : [ ],writeConcernErrors : [ ],nInserted : 2,nUpserted : 0,nMatched : 0,nModified : 0,nRemoved : 0,upserted : [ ] }) // 批量插入成功db.users.find() { _id : ObjectId(643a513d73f16a13ae248f42), name : pjl, age : 18 } { _id : ObjectId(643a51db73f16a13ae248f44), name : pjl2, age : 19 } { _id : ObjectId(643a51db73f16a13ae248f45), name : pjl3, age : 20 } // 换字段名和字段长度也能插入成功db.users.save({name2: pjl, age2: 18, tel: 131111111}) WriteResult({ nInserted : 1 })db.users.find() { _id : ObjectId(643a513d73f16a13ae248f42), name : pjl, age : 18 } { _id : ObjectId(643a51db73f16a13ae248f44), name : pjl2, age : 19 } { _id : ObjectId(643a51db73f16a13ae248f45), name : pjl3, age : 20 } { _id : ObjectId(643a529a73f16a13ae248f46), name2 : pjl, age2 : 18, tel : 131111111 }Tip向 mongo 表中插入数据非常自由什么字段、什么类型都可以。 表格-删除数据 通过 db.users.remove({age2:18}) 可以删除 age218 的数据通过 db.users.remove({}) 删除 users 表中所有数据。请看示例 // 目前有4条数据db.users.find() { _id : ObjectId(643a513d73f16a13ae248f42), name : pjl, age : 18 } { _id : ObjectId(643a51db73f16a13ae248f44), name : pjl2, age : 19 } { _id : ObjectId(643a51db73f16a13ae248f45), name : pjl3, age : 20 } { _id : ObjectId(643a529a73f16a13ae248f46), name2 : pjl, age2 : 18, tel : 131111111 }// 可以删除 age218 的数据db.users.remove({age2:18}) WriteResult({ nRemoved : 1 })db.users.find() { _id : ObjectId(643a513d73f16a13ae248f42), name : pjl, age : 18 } { _id : ObjectId(643a51db73f16a13ae248f44), name : pjl2, age : 19 } { _id : ObjectId(643a51db73f16a13ae248f45), name : pjl3, age : 20 }// 删除 users 表中所有数据是 db.users.remove({})。db.users.remove() 会报错db.users.remove() 2023-04-16T09:10:55.8590800 E QUERY [thread1] Error: remove needs a query : DBCollection.prototype._parseRemovesrc/mongo/shell/collection.js:357:1 DBCollection.prototype.removesrc/mongo/shell/collection.js:382:18 (shell):1:1 // 删除 users 表中所有数据db.users.remove({}) WriteResult({ nRemoved : 3 })db.users.find()表格-修改数据 通过 db.users.update({name:pjl2}, {$set: {age: 20}}) 修改 namepjl2 的数据将 age 改为 20。 Tip直接 db.users.update({name:pjl}, {age: 19}) 会替换整条数据。 \$inc 指增加如果需要减去则将数字改成负数。 示例如下 db.users.find() { _id : ObjectId(643b4d0cd21fdd4d6f0b0484), name : pjl, age : 18 } { _id : ObjectId(643b4d17d21fdd4d6f0b0486), name : pjl2, age : 19 } { _id : ObjectId(643b4d17d21fdd4d6f0b0487), name : pjl3, age : 20 } { _id : ObjectId(643b4d1fd21fdd4d6f0b0488), name2 : pjl, age2 : 18, tel : 131111111 } // 修改 namepjl 的数据将 age改为19db.users.update({name:pjl}, {age: 19}) WriteResult({ nMatched : 1, nUpserted : 0, nModified : 1 }) // 替换了条数据db.users.find() { _id : ObjectId(643b4d0cd21fdd4d6f0b0484), age : 19 } { _id : ObjectId(643b4d17d21fdd4d6f0b0486), name : pjl2, age : 19 } { _id : ObjectId(643b4d17d21fdd4d6f0b0487), name : pjl3, age : 20 } { _id : ObjectId(643b4d1fd21fdd4d6f0b0488), name2 : pjl, age2 : 18, tel : 131111111 } // 通过 $set 成功更改 age 而不影响其他字段db.users.update({name:pjl2}, {$set: {age: 20}}) WriteResult({ nMatched : 1, nUpserted : 0, nModified : 1 })db.users.find() { _id : ObjectId(643b4d0cd21fdd4d6f0b0484), age : 19 } { _id : ObjectId(643b4d17d21fdd4d6f0b0486), name : pjl2, age : 20 } { _id : ObjectId(643b4d17d21fdd4d6f0b0487), name : pjl3, age : 20 } { _id : ObjectId(643b4d1fd21fdd4d6f0b0488), name2 : pjl, age2 : 18, tel : 131111111 } // 给 age 增加1db.users.update({name:pjl2}, {$inc: {age: 1}}) WriteResult({ nMatched : 1, nUpserted : 0, nModified : 1 })db.users.find() { _id : ObjectId(643b4d0cd21fdd4d6f0b0484), age : 19 } { _id : ObjectId(643b4d17d21fdd4d6f0b0486), name : pjl2, age : 21 } { _id : ObjectId(643b4d17d21fdd4d6f0b0487), name : pjl3, age : 20 } { _id : ObjectId(643b4d1fd21fdd4d6f0b0488), name2 : pjl, age2 : 18, tel : 131111111 } // 给 age 减去1db.users.update({name:pjl2}, {$inc: {age: -1}}) WriteResult({ nMatched : 1, nUpserted : 0, nModified : 1 })db.users.find() { _id : ObjectId(643b4d0cd21fdd4d6f0b0484), age : 19 } { _id : ObjectId(643b4d17d21fdd4d6f0b0486), name : pjl2, age : 20 } { _id : ObjectId(643b4d17d21fdd4d6f0b0487), name : pjl3, age : 20 } { _id : ObjectId(643b4d1fd21fdd4d6f0b0488), name2 : pjl, age2 : 18, tel : 131111111 }表格-查询数据 首先清空 users 表并插入6条数据。 find 通过 db.users.find() 查询所有数据 db.users.find() { _id : ObjectId(643bb3dfd21fdd4d6f0b048a), name : peng, age : 19, tel : 0730-1231 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048b), name : jia, age : 29, tel : 0730-1232 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048c), name : li, age : 39, tel : 0730-1233 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048d), name : pengjia, age : 49, tel : 0730-1234 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048e), name : pengjiali, age : 59, tel : 0730-1235 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048f), name : jiali, age : 69, tel : 0730-1236 }大于小于 $gt - 大于$gte - 大于等于$lt - 小于$lte - 小于等于 // 查询 age 大于 50 的数据db.users.find({age:{$gt: 50}}) { _id : ObjectId(643bb3dfd21fdd4d6f0b048e), name : pengjiali, age : 59, tel : 0730-1235 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048f), name : jiali, age : 69, tel : 0730-1236 } // 查询 age 大于 69 的数据db.users.find({age:{$gt: 69}}) // 查询 age 大于等于 69 的数据db.users.find({age:{$gte: 69}}) { _id : ObjectId(643bb3dfd21fdd4d6f0b048f), name : jiali, age : 69, tel : 0730-1236 } // age 小于 20 db.users.find({age:{$lt: 20}}) { _id : ObjectId(643bb3dfd21fdd4d6f0b048a), name : peng, age : 19, tel : 0730-1231 } // 查询 age 大于 10小于 40 的数据db.users.find({age:{$gt:10, $lt:40}}) { _id : ObjectId(643bb3dfd21fdd4d6f0b048a), name : peng, age : 19, tel : 0730-1231 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048b), name : jia, age : 29, tel : 0730-1232 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048c), name : li, age : 39, tel : 0730-1233 }单条件 db.users.find({name: jia}) - 查询 name 等于 jia 的数据db.users.find({name: /jia/}) - 查询 name 中包含 jia 的数据db.users.find({name: /jia$/}) - 查询 name 中以 jia 结尾的数据 // 查询 name 等于 jia 的数据db.users.find({name: jia}) { _id : ObjectId(643bb3dfd21fdd4d6f0b048b), name : jia, age : 29, tel : 0730-1232 } // 查询 name 中包含 jia 的数据db.users.find({name: /jia/}) { _id : ObjectId(643bb3dfd21fdd4d6f0b048b), name : jia, age : 29, tel : 0730-1232 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048d), name : pengjia, age : 49, tel : 0730-1234 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048e), name : pengjiali, age : 59, tel : 0730-1235 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048f), name : jiali, age : 69, tel : 0730-1236 } // 查询 name 中以 jia 结尾的数据db.users.find({name: /jia$/}) { _id : ObjectId(643bb3dfd21fdd4d6f0b048b), name : jia, age : 29, tel : 0730-1232 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048d), name : pengjia, age : 49, tel : 0730-1234 }多条件 db.users.find({$or: [{age: 19}, {name: jia}]}) 查询 age19 或 namejia // 查询 age19 或 namejiadb.users.find({$or: [{age: 19}, {name: jia}]}) { _id : ObjectId(643bb3dfd21fdd4d6f0b048a), name : peng, age : 19, tel : 0730-1231 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048b), name : jia, age : 29, tel : 0730-1232 }列过滤 db.users.find({}, {name: 1}) - 只显示 name 这个字段。默认主键回返回。1 是显示0指不显示db.users.find({}, {name: 1, age: 1, _id: 0}) - 只要 name 和 age 字段主键不要 // 只显示 name 这个字段。默认主键回返回db.users.find({}, {name: 1}) { _id : ObjectId(643bb3dfd21fdd4d6f0b048a), name : peng } { _id : ObjectId(643bb3dfd21fdd4d6f0b048b), name : jia } { _id : ObjectId(643bb3dfd21fdd4d6f0b048c), name : li } { _id : ObjectId(643bb3dfd21fdd4d6f0b048d), name : pengjia } { _id : ObjectId(643bb3dfd21fdd4d6f0b048e), name : pengjiali } { _id : ObjectId(643bb3dfd21fdd4d6f0b048f), name : jiali } // 只显示 name 这个字段主键也不要db.users.find({}, {name: 1, _id: 0}) { name : peng } { name : jia } { name : li } { name : pengjia } { name : pengjiali } { name : jiali } // 只要 name 和 age 字段主键不要db.users.find({}, {name: 1, age: 1, _id: 0}) { name : peng, age : 19 } { name : jia, age : 29 } { name : li, age : 39 } { name : pengjia, age : 49 } { name : pengjiali, age : 59 } { name : jiali, age : 69 }排序 通过 db.users.find().sort({age: -1}) 执行 age 逆序正序则为1。 // age 逆序db.users.find({}, {age:1}).sort({age: -1}) { _id : ObjectId(643bb3dfd21fdd4d6f0b048f), age : 69 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048e), age : 59 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048d), age : 49 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048c), age : 39 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048b), age : 29 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048a), age : 19 } // age 正序db.users.find({}, {age:1}).sort({age: 1}) { _id : ObjectId(643bb3dfd21fdd4d6f0b048a), age : 19 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048b), age : 29 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048c), age : 39 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048d), age : 49 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048e), age : 59 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048f), age : 69 }分页 分页可以通过 skip 和 limit实现。例如 db.users.find().skip(2).limit(2) 查询第二页。跳过2条查询2条。 db.users.find() { _id : ObjectId(643bb3dfd21fdd4d6f0b048a), name : peng, age : 19, tel : 0730-1231 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048b), name : jia, age : 29, tel : 0730-1232 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048c), name : li, age : 39, tel : 0730-1233 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048d), name : pengjia, age : 49, tel : 0730-1234 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048e), name : pengjiali, age : 59, tel : 0730-1235 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048f), name : jiali, age : 69, tel : 0730-1236 } // 查询前3条db.users.find().limit(3) { _id : ObjectId(643bb3dfd21fdd4d6f0b048a), name : peng, age : 19, tel : 0730-1231 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048b), name : jia, age : 29, tel : 0730-1232 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048c), name : li, age : 39, tel : 0730-1233 } // 第一页。跳过0条查询2条db.users.find().skip(0).limit(2) { _id : ObjectId(643bb3dfd21fdd4d6f0b048a), name : peng, age : 19, tel : 0730-1231 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048b), name : jia, age : 29, tel : 0730-1232 } // 第二页。跳过2条查询2条db.users.find().skip(2).limit(2) { _id : ObjectId(643bb3dfd21fdd4d6f0b048c), name : li, age : 39, tel : 0730-1233 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048d), name : pengjia, age : 49, tel : 0730-1234 } // 第三页。跳过4条查询2条db.users.find().skip(4).limit(2) { _id : ObjectId(643bb3dfd21fdd4d6f0b048e), name : pengjiali, age : 59, tel : 0730-1235 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048f), name : jiali, age : 69, tel : 0730-1236 } // 先 age 逆序在取2条db.users.find().sort({age: -1}).skip(0).limit(2) { _id : ObjectId(643bb3dfd21fdd4d6f0b048f), name : jiali, age : 69, tel : 0730-1236 } { _id : ObjectId(643bb3dfd21fdd4d6f0b048e), name : pengjiali, age : 59, tel : 0730-1235 }通过 count() 查询记录数例如 db.users.find({name: jia}).count() // 总共 6 条db.users.find().count() 6 // 符合条件的共 1 条db.users.find({name: jia}).count() 1db.users.find({name: /jia/}).count() 4db.users.findOne() - 查询第一条 // 查询第一条db.users.findOne() {_id : ObjectId(643bb3dfd21fdd4d6f0b048a),name : peng,age : 19,tel : 0730-1231 }项目目录划分 程序那么复杂不可能全写在一起笔者做如下分层 路由层 - 匹配路由调用控制层控制层 - 取得前端请求数据加工处理比如调用数据库services层在返回数据给前端服务层 - 引用创建的数据库模型对数据进行增删改查模型层 - 创建数据库模型这里是创建表 以用户模块为例在这4层中分别创建如下 js - services // 服务层- UserService.js // User 模块的服务层 - routes // 路由- UserRouter.js // User 模块的路由。比如登录、登录 - models // 模型层- UserModel.js // User Model - controllers // 控制层- UserController.js 连接数据库 前面我们操作数据库是直接进入 mongo shell 操作: // 创建并切换到数据库 pjl_db use pjl_db// 创建 users 表这里叫集合 db.createCollection(users)现在我们需要通过 node 来操作数据库。 启动mongo服务 通过 mongod --dbpath/var/lib/mongodb --bind_ip0.0.0.0 --port27017 启动mongo服务未设置数据库密码。其中 0.0.0.0 用户远程连接端口是 27017。 如果需要后台启动关闭终端服务也不会停止需要指定日志路径就像这样 rootlinux:/home/pjl# mongod --dbpath/var/lib/mongodb --fork --logpath/var/log/mongodb/mongodb.log --bind_ip0.0.0.0 --port27017 about to fork child process, waiting until server is ready for connections. forked process: 133354 child process started successfully, parent exiting查看 mongod 进程 rootlinux:/home/pjl# ps aux |grep mongod root 133354 7.5 1.5 976348 62496 ? Sl 09:46 0:00 mongod --dbpath/var/lib/mongodb --fork --logpath/var/log/mongodb/mongodb.log --bind_ip0.0.0.0 --port27017 root 133383 0.0 0.0 12120 716 pts/0 S 09:47 0:00 grep --colorauto mongod rootlinux:/home/pjl#Tip还可以通过指定配置文件启动 rootlinux:/home/pjl# mongod -f /etc/mongodb.conf // 没反应通过 tail -10 日志 能看到输出另起窗口进入 mongo shell运行 show dbs 报错如下 // 笔者将配置文件中端口改为 27027 rootlinux:/var/log/mongodb# mongo --port27027 MongoDB shell version v3.6.8 connecting to: mongodb://127.0.0.1:27027/ Implicit session: session { id : UUID(dc184887-824d-474a-a942-3d42ff1a21bf) } MongoDB server version: 3.6.8show dbs 2023-04-21T09:52:04.8240800 E QUERY [thread1] Error: listDatabases failed:{ok : 0,errmsg : there are no users authenticated,code : 13,codeName : Unauthorized } : _getErrorWithCodesrc/mongo/shell/utils.js:25:13 Mongo.prototype.getDBssrc/mongo/shell/mongo.js:67:1 shellHelper.showsrc/mongo/shell/utils.js:860:19 shellHelpersrc/mongo/shell/utils.js:750:15 (shellhelp2):1:1网友说是 安装mongo数据库时配置文件中加了安全权限的设置解决请看这里 安装 mongoose 通过 npm i mongoose -D 安装 mongoose —— Mongoose is a MongoDB object modeling tool。 通过 mongoose 操作数据库非常方便 连接数据库 连接数据库很简单只需要先启动数据库服务然后在启动应用前连接数据库即可。代码如下 // bin/www.jsvar http require(http);// 引入数据库require(../config/db.config) var port normalizePort(process.env.PORT || 3000);// config/db.config.jsconst mongoose require(mongoose) // mongo服务 ip mongoose.connect(mongodb://192.168.1.223:27017/pjl_db) mongoose.connection.once(open, () {console.log(数据库连接成功) })通过 mongo shell 查到目前只有3个数据库 show dbs admin 0.000GB config 0.000GB local 0.000GB启动应用控制台输出 数据库连接成功: PS E:\spug-back-end npm run start spug-back-end0.0.0 startnodemon ./bin/www[nodemon] 2.0.22 [nodemon] to restart at any time, enter rs [nodemon] watching path(s): *.* [nodemon] watching extensions: js,mjs,json [nodemon] starting node ./bin/www 数据库连接成功发现 pjl_db 数据库自动被创建。 show dbs admin 0.000GB config 0.000GB local 0.000GB pjl_db 0.000GBTip有了数据库还得需要表才能对数据进行增、删、改、查。在 mongoose 中需要创建一个 model模型可以把他当做一张表或一条记录比如下文登录模块的 UserModel.js 就是一个 model向 model 插入一条数据时mongoose 会自动创建一张名为 users 的表或集合。 登录 这里我们完成系统登录模块的开发。 app.js app.js 引入用户路由。 // app.js var indexRouter require(./routes/index); var usersRouter require(./routes/users);const UserRouter require(./routes/UserRouter)app.use(/users, usersRouter);app.use(UserRouter);UserRouter.js 定义登录路由/user/login路由匹配成功进入控制层处理。 // routes/UserRouter.js// 用户路由 var express require(express); var router express.Router(); const UserController require(../controllers/UserController.js) /* POST users listing. */ router.post(/user/login, UserController.login);module.exports router;UserController.js 控制层调用服务层如果数据库能通过用户名和密码查询到该用户则表明登录成功否则返回用户名密码不匹配。 // controllers/UserController.jsconst UserService require(../services/UserService)const UserModel require(../models/UserModel) const UserController {login: async (req, res) {// req.body - 例如 {username:pjl,password:123456}console.log(res.body, JSON.stringify(res.body))var result await UserService.login(req.body)if(result.length 0){res.send({code: -1,error: 用户名密码不匹配})}else{res.send({code: 0,error: })}} }module.exports UserControllerUserService.js 模型层通过 model 查找数据库 // services/UserService.jsconst UserModel require(../models/UserModel.js) const UserService {login: async ({username, password}) {return UserModel.find({username,password})} }module.exports UserServiceUserModel.js mongoose 通过 model 创建表。 // models/UserModel.js// model 与表一一对应 const mongoose require(mongoose) const Schema mongoose.Schema // 通过 schema 限制一下集合表否则什么都能传入太自由了不好 const Usertype {username: String,password: String,// 性别gender: Number,// 头像avatar: String,// 角色role: Number, // 管理员1编辑2 }const UserModel mongoose.model(user, new Schema(Usertype)) module.exports UserModel测试 这里笔者在 git bash 中使用 curl客户端的url 模拟登录post 用户名密码 Administrator ~/Desktop $ curl -X POST -d usernamepjl -d password123456 http://localhost:3000/user/login% Total % Received % Xferd Average Speed Time Time Time CurrentDload Upload Total Spent Left Speed 100 76 100 48 100 28 1425 831 --:--:-- --:--:-- --:--:-- 2533{code:-1,error:用户名密码不匹配}由于 users 表中没有数据当然也就查询不到返回 {code:-1,error:用户名密码不匹配}。 笔者手动插入该条用户信息 use pjl_db switched to db pjl_dbdb.users.save({username: pjl, password: 123456}) WriteResult({ nInserted : 1 })再次登录就能查询到 {code:0,error:}    Administrator ~/Desktop $ curl -X POST -d usernamepjl -d password123456 http://localhost:3000/user/login% Total % Received % Xferd Average Speed Time Time Time CurrentDload Upload Total Spent Left Speed 100 51 100 23 100 28 1730 2106 --:--:-- --:--:-- --:--:-- 5100{code:0,error:}
http://wiki.neutronadmin.com/news/51426/

相关文章:

  • 微网站预约网站开发网站运行平台包括
  • 网站改版注意事项直播网站开发需要多少钱
  • 网站搜索引擎优化诊断官方网站aspcms
  • 律师事务所网站建设策划方案百度云网盘登录入口
  • 华为商城的网站建设官网网站建设需求文档
  • 手机网站开发模拟手机房地产互联网推广
  • 网站设计好了如何上传到自己搭建的网上去深圳做微信商城网站
  • 那种系统做网站比较好美轮美奂的网站建设
  • 动易论坛官方网站无锡网站搜索引擎优化
  • 做外贸门户网站wordpress长文档分页
  • 网站开发客户需求文档营销助手下载app下载
  • 建设网站企业邮箱dede网站地图模板文件
  • 优秀的国外设计网站营销型网站建设0469z
  • win11优化大师网站如何seo
  • 网站如何报备软件开发定制价格表
  • wordpress数据库删除seo如何提高网站排名
  • 网龙公司有做网站吗wordpress基础安装
  • 网站怎么备案在哪里橱柜手机网站模板
  • 制作asp手机网站东莞seo优化指南
  • 河北建设工程信息网官方网站高要市建设局网站
  • 东菀高端网站建设博客模板wordpress
  • wordpress换域名后网站地址怎么办房产备案信息查询系统官网
  • 满山红厦门网站建设泸州房地产新闻
  • 漳州网站开发去博大钱少a阿里巴巴的网站建设
  • 公司做的网站版权归谁所有凡客诚品为什么没落了
  • 衡水网站优化推广域名怎么创建网站吗
  • 小伙做网站做养生网站需要什么资质
  • 男女做恩爱视频网站十大免费网站模板网站
  • 网站推广的基本方法对于大部分网站来说都是适用的锦州网站建设多少钱
  • 外贸网站建设和网站推广要怎么做互联网营销案例分析