Express + mongoDB + nodejs

本文介绍如何使用Express框架和MongoDB数据库开发Web接口,包括安装Express和mongoose模块,建立MongoDB连接,创建文档模型,实现数据的增删查改操作。

Express + mongoDB开发web接口

  • Experss开发web接口
  • 菲关系型数据库mongodb
  • 使用nodejs的mongoose模块链接和操作mongodb

Express

基于nodejs, 快速、开放、极简的web开发框架

  • npm install express --save 安装express
  • hello world应用
  • 监听路由和响应内容,使用nodemon自动重启npm insyall -g nodemon
  • app.get、app.post分别开发get和post接口
  • app.use使用模块
  • res.send、res.json、res.sendfile响应不同的内容

mongoose + mongodb

  • npm install mongoose --save安装mongoose 1、连接mongodb
const DB_URL = 'mongodb://localhost:27017/userdetails';
mongoose.connect(DB_URL);
mongoose.connection.on('connected', (err, doc) => {
  if (!err) {
    console.log(doc);
    console.log('链接成功!');
  }
})
复制代码

2、 创建mongo文档、字段(类似mysql的表)

  • model创建模型
var MongooseUser = mongoose.model('mongooseuser', new mongoose.Schema({
  userName: {type: String, require: true},
  age: {type: Number, require: true},
  discripe: {type: String}
}));
复制代码

3、数据的增删查改(CURD)

更多API官网查看,多练习

  • 数据新增(create)
MongooseUser.create({
  userName: '苏苏',
  age: 20,
  discripe: '广州云徙科技有限公司-前端架构师'
}, (err, doc) => {
  if (!err) {
    console.log('数据新增成功!');
  }
});
复制代码
  • 删除数据
User.deleteOne({
  userName: '大海'
}, (err, doc) => {
  if (!err) {
    console.log('数据删除成功');
  }
});
复制代码
  • 修改数据
User.updateOne({userName: '苏苏'}, {$set: {age: 18}}, (err, data) => {
  if (!err) {
     console.log('修改数据成功');
   }
 })
复制代码
  • 查找数据
User.find({userName: '苏苏'});
复制代码

转载于:https://juejin.im/post/5bc9454fe51d450e742921fc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值