美文网首页
Nodejs使用mongoose

Nodejs使用mongoose

作者: yoolika | 来源:发表于2019-01-03 13:35 被阅读0次

    框架:nodejs+express+mongoose+es6

    import mongoose from 'mongoose'
    import config from '../config'
    var DB_URL = config.mongodb_url;
    mongoose.Promise = global.Promise;
    /**
     * 连接
     */
    mongoose.connect(DB_URL);
    
    /**
      * 连接成功
      */
    mongoose.connection.on('connected', function () {
        console.log('Mongoose connection success to ' + DB_URL);
    });
    
    /**
     * 连接异常
     */
    mongoose.connection.on('error',function (err) {
        console.log('Mongoose connection error: ' + err);
    });
    
    /**
     * 连接断开
     */
    mongoose.connection.on('disconnected', function () {
        console.log('Mongoose connection disconnected');
    });
    
    export default mongoose
    

    创建Model

    import mongoose from '../db/mongooseDb'
    
    
    var Schema = mongoose.Schema;
    
    var UsersSchema = new Schema({
        uid : { type: String },
        type: {type: Number}, /
        uname: {type: String},
        logintime : { type: Date, default: Date.now}                      
        }, { versionKey: false });//去掉版本控制
    
    const Users = mongoose.model('User',UsersSchema);
    
    export default Users
    

    使用

    async getUserInfo(){
       var userInfo = await  UsersModel.findOne({ 'uid': result.UId })
    }
    
    

    具体的增删改查 网上有很多 在这里不做详细
    https://segmentfault.com/a/1190000008245062

    相关文章

      网友评论

          本文标题:Nodejs使用mongoose

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