MongoDB在Node.js中的使用

作者: yellow超 | 来源:发表于2016-08-29 02:14 被阅读754次

    开场白

    **MongoDB **是一个基于分布式文件存储的非关系型数据库,由C++语言编写,旨在为WEB应用提供可扩展的高性能数据存储解决方案。推荐运行在64位平台,因为MongoDB在32位模式运行时支持的最大文件尺寸为2GB,64位平台则非常大。MongoDB中有三种元素:数据库(database),集合(collection),文档(document),其中“集合” 对应关系数据库中的“表”,“文档”对应关系数据库的“行”。其中MongoDB 是文档数据库, 面向集合(collection)的数据库。

    使用者留言

    一个词: 简单, 没有了传统数据库那么多的限制,让开发者更多精力放在处理业务逻辑上,学习曲线很平滑,因为没有新的查询语言学习。代码是简洁的。毕竟,无须任何其他ORM,封装可以非常简单。你的代码是未来的保证。向你的对象增加更多的字段是很轻松的。因此,需求变化了,你可以很快修改代码以便适应。

    Node.js 中使用MongoDB(几乎是标配)

    • mac中安装MongoDB
      brew install mongodb

    • node.js 中使用mongoose第三方库来管理MongoDB
      npm install mongoose --save
      为什么使用mongoose呢,原因很简单,官方的驱动都是以回调的方式的API,而mongoose封装成了promise,就可以使用await/async了

    *配置连接DB信息,并导出连接的对象

    import mongoose from 'mongoose'
    
    const options = {
        user: 'admin',
        pwd: '123456',
        host: 'localhost',
        port: '27017',
        database: 'hollywood',
        authSource: 'admin',
    }
    
    const uri = `mongodb://${options.user}:${options.pwd}@${options.host}:${options.port}/${options.database}?authSource=${options.authSource}`
    
    mongoose.Promise = global.Promise //需要
    mongoose.connect(uri)
    
    export default mongoose
    
    

    *定义一个模型的概要,类似于关系型数据库中的定义表结构

    import db from '../db.js'
    import logger from '../logger'
    
    const Schema = db.Schema
    
    //account对应的字段
    const accountSchema = new Schema(
        {
            name: { type: String, maxlength: 15 },
            password: { type: String, maxlength: 20 },
            gender: { type: String, enum: ['male', 'female'] },
            email: { type: String, maxlength: 25 },
            avatar: { type: String },
            age: { type: Number },
            create_date: { type: Date },
            update_date: { type: Date },
        },
        {
            versionKey: false,
        },
    )
    
    //当account执行save()前,执行该代码片段,有点类似于中间件(这个方法内容仅仅是介绍pre()的使用方法)
    accountSchema.pre('save', function(next) {
        const currentDate = new Date()
        if (!this.create_date) {
            this.create_date = currentDate
        } else {
            this.update_date = currentDate
        }
        next()
    })
    
    //当account执行save()后
    accountSchema.post('save', function(doc) {
      logger.info(`Account ${doc._id} was saved.`)
    })
    
    //定义模型的方法
    accountSchema.methods.sayHi = () => (console.log('sayHi()!!!!!'))
    
    const Account = db.model('Account', accountSchema)
    
    export default Account
    
    

    *保存到数据库, 并返回一个保存到数据库的对象

    import Account from './model'
    
    export default class AccountService {
        static async save(json) {
            const accountModel = new Account(json)
            const account = await accountModel.save()
            return account
        }
    }
    

    CRUD的操作

    • R
      Account.find({ name: 'yellow' })

    • U (完全可以自己在封装一层)

    const account = await Account.find({ name: 'yellow' })
    account.name = 'hzc'
    await account.save()
    
    • D
    const account = await Account.find({ name: 'yellow' })
    await account.remove()
    

    总结

    使用确实方便,但是也会有很多坑等待你来挖,毕竟是新事物, 需要不断的发展,但是你同它一起进步,一起发展不是已经很有意思的事情吗。

    相关文章

      网友评论

      本文标题:MongoDB在Node.js中的使用

      本文链接:https://www.haomeiwen.com/subject/esdxettx.html