nodejs+express+mongoose连接数据库

  •  安装express
  • //express安装生成器
    npm install -g express-generator
    执行命令express -h
    这里可以看到一些命令选项
      
    Options:
    
        -h, --help          output usage information
            --version       output the version number
        -e, --ejs           add ejs engine support
            --hbs           add handlebars engine support
            --pug           add pug engine support
        -H, --hogan         add hogan.js engine support
            --no-view       generate without view engine
        -v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
        -c, --css <engine>  add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
            --git           add .gitignore
        -f, --force         force on non-empty directory
    
    
    执行 express -e生成如下代码目录:
    ├── app.js
    ├── bin
    │   └── www
    ├── package.json
    ├── public
    │   ├── images
    │   ├── javascripts
    │   └── stylesheets
    │       └── style.css
    ├── routes
    │   ├── index.js
    │   └── users.js
    └── views
        ├── error.ejs
        ├── index.ejs
    
  • 安装mongoose,并配置启动文件

        

//安装mongoose
npm install mongoose --save
//在项目目录下创建config目录,并在创建db.config.js(名字随意)文件,连接数据库的配置文件

db.config.js内容
const mongoose = require("mongoose")

mongoose.connect('mongodb://127.0.0.1:27017/reactDataBase').then(res => {
    console.log("数据库存连接成功")
}).catch((e) => {
    console.log("连接失败了", e)
})

在bin目录下的www中引入配置文件

到这里就可以npm start (在package.json中可以看启动命令)启动服务了

(注意:在启动之前先开启MongoDb服务)

  • 创建基本模型(文档)

在项目目录下创建UserModel模型 

//引入mongoose
const mongoose = require("mongoose")

const Schema = mongoose.Schema
//定义文档的结构
const UserType = {

    avatar:String,
    //对字段有要求,验证,写成对象形式
    name: {
        type: String,
        required: [true, "必填name"],
        minLength: [2, "最小长度为2"],
        maxLength: [7, '最大长度为7']

    },
    password: {
        type: String,
        required: [true, "必填password"],
        minLength: [6, "最小长度为6"],
        maxLength: [16, '最大长度为16']
    },
    description: {
        type: String,
        maxLength: [30, "最大长度为30"]
    },
    sex: {
        type: String,
        enum: {
            values: ['male', 'woman', 'secrecy'],
            message: "只能从male | woman | secrecy选择"
        },
    }
}
//生成模型
const UseModel = mongoose.model("user", new Schema(UserType))

//导出模型
module.exports = UseModel
  • 基本使用

//这里就用自动生成的user路由来简单的使用

var express = require('express');
var router = express.Router();
//引入模型
const UseModel = require("../models/UserModel")
//浏览器发送请求127.0.0.1:3000/user
router.get('/', function (req, res, next) {
  try {
//假设有个传过来的数据是temp
    const temp = {
        name: "dsay",
        password: "jfdhff",
        sex: "male"
      }

//添加数据到数据库
   UseModel.create(temp)
   res.send({
     "ok": "ok"
   })
 } catch (error) {
   throw new error
 }
});

module.exports = router;

这里用的可视化工具可以看到已经有数据了

 

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值