2022-09-04 mongodb基本使用

具体的操作查看mongodb官网,如果使用了mongoose第三方模块查阅mongoose中文官网

mongodb的集合相当于数据库下的一个表格,也就是一张数据表
在nodejs中可以直接把集合对象给暴露出去


// 创建用户集合
// 引入mongoose第三方模块
const mongoose = require('mongoose')
const bcrypt = require('bcryptjs')
    // 创建集合规则
const userSchema = mongoose.Schema({
    username: {
        type: String,
        required: true,
        minlenth: 2,
        maxlenth: 20
    },
    password: {
        type: String,
        required: true,
        minlenth: 2,
        maxlenth: 20
    }
})

// 创建user集合实例
const User = mongoose.model('User', userSchema)


async function createUser() {
    const salt = await bcrypt.genSalt(10)
    const pass = await bcrypt.hash('123456', salt)
    User.create({
        username: 'admin',
        password: pass
    })
}
//createUser()
// // 初始化用户
// User.create({
//     username: 'admin',
//     password: '123456'
// }).then(() => {
//     console.log('用户创建成功');
// }).catch(() => {
//     console.log('用户创建失败');
// })

// 将用户集合作为模块成员进行导出
module.exports = {
    User
}
posted @ 2024-02-17 21:10  lovevivi121  阅读(9)  评论(0)    收藏  举报  来源