mongodb 结合 mongoose实现用户增删改查的简单示例

  • 分析用户模块的属性(比如姓名,性别,年龄等等)
  • 编写用户模块的结构()
  • 使用Json Schema生成用户model

这里的model就是mvc这种架构里的model
通常用于数据库的操作,定义数据库的表结构

users.js

const mongoose = require('mongoose');

用mongoose提供的方法
const {
    
    Schema,model} = mongoose;
用这个方法类实例化一个用户的schema
const userSchema = new Schema({
    
    
//不管输入什么类型,都自动转成type后你定义的类型
  name:{
    
     type:string, required:true },
  age: {
    
     type:Number, required:false }
})

这就是设计的简单userschema模型
然后用mongoose中的model方法这个生成模型并导出

//第一个参数是mongodb里的某个集合的名称,
//第二个参数是传入的schema
//这样就建好了一个User模型,导出的模型也是一个类
model.exports = model('User', userSchema)
const User = require('user文件路径')

class UsersCtl {
    
    
  //查询用户接口
  async find(ctx) {
    
    
	ctx.body = await User.find()
  }
  //通过id查询用户接口
   async findById(ctx) {
    
    
	const user = await User.findById(ctx.params.id);
	if (!user) {
    
     ctx.throw(404, '用户不存在')}
  }
  //其他增删改查接口类似..
  
}

猜你喜欢

转载自blog.csdn.net/m0_48446542/article/details/109125517