mongoose 与schema 和model

10 篇文章 0 订阅

在Node项目中使用mongoDB数据库,一般来说是使用Moogose进行连接,所以现在就来介绍一下

安装

yarn add mongoose 
//或者npm i mongoose

连接

const mongoose = require(“mongoose”);
mongoose.connect(‘mongodb://localhost/my_database’);
建立schema 和model

  • shema 相当于对表结构的定义
  • model 定义表 其实
  • 在MongoDB中不能称为表,应该为文档 shema

shema

const mongoose = require('mongoose');
 
mongoose.connect('mongodb://localhost/my_database');
 
const {Schema} = mongoose;
//  用户对象模型
const userSchema = new Schema({
  name: {
    type: String, //类型
    default: Date.now // 默认值
  },
  avatar: {
        type: String,
        required: true //必须有值
  },
  user: String,
  passworld: String,
  hash: String,
  score: Number,
  learn: Array,
  message: Array,
  star: Array,
  sign: Array,
  signdate: String,
  isregister: Boolean,
});

Model

Model是由Schema编译而成的假想(fancy)构造器,具有抽象属性和行为。Model的每一个实例(instance)就是一个document。document可以保存到数据库和对数据库进行操作。

//创建并导出model
const db= {
  User: mongoose.model('MUser', muserSchema),
};
module.exports = db;

现在我们就完成了mongodb的数据连接,数据对象模型的创建。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值