阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

使用Nodejs连接MongoDB的详细步骤

155次阅读
没有评论

共计 3682 个字符,预计需要花费 10 分钟才能阅读完成。

使用 Nodejs 连接 MongoDB 的详细步骤

步骤一

  • 安装 nodejs,express,mongodb,mongoose(这里就不多说了~~)

    步骤二

    用 express 快速创建一个项目的框架

    express -e project
  • 参数说明:-e:使用的模板类型,project: 项目名称

    创建好项目后

  • 进入到创建的项目目录
  • cd project
  • 安装 package.json 文件中项目所依赖的包
  • cnpm install
  • 启动项目
  • npm run start
  • 目录讲解
    • node_modules 项目中依赖的包
    • public 静态目录(放公共资源的)
    • routes 路由(存放一些路由文件)
    • views 视图(存放页面文件)
    • app.js 项目的入口文件

      步骤三

      设计数据库

  • 打开 cmd(以管理员的身份)
  • 连接数据库(出现版本号就代表连接成功啦)
  • mongo
  • 查看所有数据库
  • show dbs
  • 创建一个名为 admin 的数据库
  • use admin
  • 进入 admin
  • db
  • 在 admin 下创建一张表
  • db.createCollection("goods")
  • 查看表
  • show tables

    连接数据库

  • 在项目根目录下创建一个 model 文件夹,然后在创建一个 data.js(存放数据)和 goods.js
  • goods.js 如下
  • // 引入模块
    var mongoose=require('mongoose');
    // 引入 data.js
    var seafoodList=require('./data.js').seafoodList
    // 连接数据库
    mongoose.connect('mongodb://localhost:27017/admin')
    // 得到数据库连接句柄
    var db=mongoose.connection;
    // 通过 数据库连接句柄,监听 mongoose 数据库成功的事件
    db.on('open',function(err){if(err){console.log('数据库连接失败');
            throw err;
        }
        console.log('数据库连接成功')
    })
    // 定义表数据结构
    var seafoodModel=new mongoose.Schema({id:Number,
        name:String,
        desc:String,
        discount:Number,
        price:Number,
        coin:Number,
        remain:String,
        img_sm:String,
        img_lg:String
    },{versionKey:false // 去除:- -v
    })
    // 将表的数据结构和表关联起来
    var seafoodModel=mongoose.model("seafoodList",seafoodModel,"goods");
    // 添加数据
    seafoodModel.insertMany(seafoodList,function(err,result){if(err){console.log("数据添加失败");
            throw err;
        }
        console.log("数据添加成功:",result);
    })
    // 导出数据
    module.exports={seafoodModel:seafoodModel}

步骤四

在 routes 下创建 goods.js

    // 引入 express 模块
    var express=require("express")
    // 引入数据模块
    var goodsData=require("../model/goods").seafoodModel;
    // 获取路由对象
    var router=express.Router();
    // 商品管理页
    router.get('/goods',function(req,res){res.render('index/index')
    })
    
    // 商品信息
    router.get('/goodsList',function(req,res){goodsData.find({},function(err,result){if(err){console.log("查询失败")
                throw err
            }
            console.log("查询结果",result)
            res.render('goods/goodsList',{title:'商品信息',goodsList:result})
        })
        
    })
    
    module.exports=router;

步骤五

在 views 下创建 goods 文件夹,在 goods 下创建 goodsList.html

  • goodsList.html 主要代码如下
  • <div class="page-content">
                    <div class="page-header">
                        <h1>
                            商品管理
                            <small>
                                <i class="icon-double-angle-right"></i>
                                 <%= title%>
                            </small>
                        </h1>
                    </div><!-- /.page-header -->
                    <!-- 主要内容 -->
                    <div class="row">
                        <table class="table table-bordered table-hover text-center">
                            <thead>
                                <tr class="success">
                                    <th class="text-center">id</th>
                                    <th class="text-center">name</th>
                                    <th class="text-center">desc</th>
                                    <th class="text-center">discount</th>
                                    <th class="text-center">coin</th>
                                    <th class="text-center">remain</th>
                                    <th class="text-center">img_sm</th>
                                    <th class="text-center">img_lg</th>
                                </tr>
    
                            </thead>
                            <tbody>
                                <% for(var item in goodsList){%>
                            <tr>
                                <td><%= goodsList[item].id%></td>
                                <td><%= goodsList[item].name%></td>
                                <td><%= goodsList[item].desc%></td>
                                <td><%= goodsList[item].coin%></td>
                                <td><%= goodsList[item].remain%></td>
                                <td><%= goodsList[item].discount%></td>
                                <td class="cut"><%= goodsList[item].img_sm%></td>
                                <td class="cut1"><%= goodsList[item].img_lg%></td>
                            </tr>
                            <% }%>
                            </tbody>
                        </table>
                    </div>
                </div><!-- /.page-content -->

    最后 ejs 转为 html

    app.set('views', path.join(__dirname, 'views'));
    app.engine(".html", ejs.__express);
    // 设置模板引擎类型
    app.set('view engine', 'html');

 

更多 MongoDB 相关教程见以下内容

MongoDB 文档、集合、数据库简介  http://www.linuxidc.com/Linux/2016-12/138529.htm

MongoDB 3 分片部署及故障模拟验证  http://www.linuxidc.com/Linux/2016-12/138529.htm

Linux CentOS 6.5 yum 安装 MongoDB  http://www.linuxidc.com/Linux/2016-12/137790.htm

CentOS 7 yum 方式快速安装 MongoDB  http://www.linuxidc.com/Linux/2016-11/137679.htm

MongoDB 的查询操作  http://www.linuxidc.com/Linux/2016-10/136581.htm

在 Azure 虚拟机上快速搭建 MongoDB 集群  http://www.linuxidc.com/Linux/2017-09/146778.htm

MongoDB 复制集原理  http://www.linuxidc.com/Linux/2017-09/146670.htm

MongoDB 3.4 远程连接认证失败  http://www.linuxidc.com/Linux/2017-06/145070.htm

Ubuntu 16.04 中安装 MongoDB3.4 数据库系统  http://www.linuxidc.com/Linux/2017-07/145526.htm

MongoDB 权威指南第 2 版 PDF 完整带书签目录 下载见 http://www.linuxidc.com/Linux/2016-12/138253.htm

MongoDB 的详细介绍:请点这里
MongoDB 的下载地址:请点这里

本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-12/149532.htm

正文完
星哥说事-微信公众号
post-qrcode
 
星锅
版权声明:本站原创文章,由 星锅 2022-01-22发表,共计3682字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中