美文网首页
express + mongodb 基础

express + mongodb 基础

作者: 丶HanGH | 来源:发表于2017-12-04 22:10 被阅读0次

Express开发web接口

基于Node.js ,快速、开放、极简的web开发框架
http://www.expressjs.com.cn

  1. 安装
    npm install express --save
  2. 在项目目录下创建server文件夹
  3. server文件夹下创建server.js
const  express = require('express');
//新建app
const app = express();

app.get('/',function (req,res) {
    res.send('<H1>Hello,World!</H1>');
});
app.get('/data',function (req,res) {
    res.json({name:"Han",course:"Hello"})
});
app.listen(9093,function () {
    console.log("服务器运行在9093端口");
});
  1. 自动重启服务器工具nodemon
    npm install -g nodemon

5.其他特性

  • app.get、app.post分别开发get和post接口
  • app.use使用模块
  • 代res.send、res.json、res.sendfile响应不同的内容

非关系型数据库mongodb

https://www.mongodb.com

  1. 使用Homebrew安装mongodb
    brew install mongodb

  2. 项目中使用
    npm install mongoose --save

  3. 启动mongodb,命令行输入
    mongod --config /usr/local/etc/mongod.conf

  4. 基本配置

const mongoose = require('mongoose');

//连接
const DB_URL="mongodb://localhost:27017/Users";

mongoose.connect(DB_URL);
mongoose.connection.on('connected',function () {
    console.log("mongodb connect success!");
});
  1. Mongoose文档
  • mongoose文档类型
    • String、Number等数据结构
    • 定create、remove、update分别用来增删改的操作
    • Find 和 findOne用来查询数据
  1. 增加数据
//新增数据
users.create({
    name: '很厉害的韩同学',
    age: 21
}, function (err, doc) {
    if (!err) {
        console.log(doc);
    } else {
        console.log(err);
    }
});
  1. 查找数据
// 查找数据
users.find({}, function (err, doc) {
    if (!err) {
        console.log(doc);
    } else {
        console.log(err);
    }
});
  1. 查找单条数据
// 查找单条数据
users.findOne({name:"Han"}, function (err, doc) {
    if (!err) {
        console.log(doc);
    } else {
        console.log(err);
    }
});
  1. 删除数据
//删除 年龄为21的数据
//result:{n:2,ok:1}  n表示删除两条数据 ok:1表示删除成功
users.remove({age: 21}, function (err, doc) {
    if (!err) {
        console.log(doc);
    } else {
        console.log(err);
    }
});
  1. 更新数据
//更新数据
//$set可以省略
// n 表示符合条件的行数  nModified 表示改动的行数 ok :1 表示更新成功
users.update({name: 'Han'}, {$set: {age: 19}}, function (err, doc) {
    if (!err) {
        console.log(doc);
    } else {
        console.log(err);
    }
});

Express 和 mongodb结合

  1. mongodb独立工具函数
  2. express使用body-parser支持post参数
  3. 使用cookie-parser存储登录信息cookie

使用Node.js的mongoose模块链接和操作mongodb


相关文章

网友评论

      本文标题:express + mongodb 基础

      本文链接:https://www.haomeiwen.com/subject/nvkfixtx.html