三、NodeJs链接MogoDB云数据库
MongoDB使用云数据库
注册用户
创建数据库
添加用户
设置白名单地址
链接数据库
使用数据库
安装mongoose
yarn add mogoose链接数据库
复制上一步的字符串,并替换掉其中的数据。例如
<password>和<dbname>在入口文件链接数据库
const mongoose = require('mongoose') // 通过配置文件导入链接字符串 const { connectionStr } = require('./config') mongoose.connect(connectionStr, { useUnifiedTopology: true, useNewUrlParser: true }, () => { console.log('链接成功了'); })
创建用户模型
新建一个
schema文件夹,在这个文件中写我们的数据库模型。例如userconst mongoose = require('mongoose') const { Schema, model } = mongoose const userSchema = new Schema({ name: { type: String, required: true } }) // 生成模型 model.exports = model('User', userSchema)实现增删改查
const User = require('../models/users') class UserCtl { async find (ctx) { ctx.body = await User.find() } async findById (ctx) { const user = await User.findById(ctx.params.id) if (!user) { ctx.throw(404, '用户不存在') } ctx.body = user } async create (ctx) { ctx.verifyParams({ name: { type: 'string', required: true }, }) const user = await new User(ctx.request.body).save() ctx.body = user } async update (ctx) { ctx.verifyParams({ name: { type: 'string', required: true }, }) const user = await User.findByIdAndUpdate(ctx.params.id, ctx.request.body) if (!user) ctx.throw(404, '修改的用户ID不存在') ctx.body = user } async delete (ctx) { const user = await User.findByIdAndRemove(ctx.params.id) if (!user) ctx.throw(404, '删除的用户ID不存在') ctx.status = 204 } } module.exports = new UserCtl()
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 小康博客!
评论
TwikooDisqusjs













