working on it ...

Filters

Explore Public Snippets

Sort by

Found 378 snippets matching: mongoose

    public by tomsim modified Jan 21, 2018  1399  1  6  0

    Simple RPC call

    Simple function to call RPC (only 1k uncompressed). Use this instead of JQuery. Alternatively, use zepto.min.js from zeptojs.com if you have 26K to spare.
    /* 
    Addapted from Paolo Manna git pmanna/mongoose_os_playground browser_rpc_service.js
    */
    
    var platform = '';
    var host = '';
    
    var defCallBack = function(response) {
      if ((response) && (response.error)) {
    	  alert(response.message);
      }
    };
    
    // Common call to RPC services on the board
    function callRPCService(cmd, params, callback) {
      if (!callback) {
    	  callback = defCallBack;
      }
      var xhttp = new XMLHttpRequest();
      
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          callback(this.response);
        }
      };
      
      xhttp.open('POST', 'rpc/' + cmd + '?' + new Date().getTime(), true);
      xhttp.responseType = 'json';
      xhttp.send(JSON.stringify(params));
    }
    
    // Discover which platform we're using, to enable/disable features
    function startup() {
      callRPCService('Config.Get',{}, function(response) {
        if (response) {
          platform = response.device.id;
          console.log('Platform is: ' + platform);
    
          var mac_id = (response.device.id.split("_"))[1];
    
          host = mac_id + '.local';
          document.getElementById("hostname").innerHTML = host;
        }
      });
    }
    
    // Reboots the microcontroller
    function rebootDevice() {
      callRPCService('Sys.Reboot',{delay_ms:500});
    }
    
    						

    public by tomsim modified Jan 21, 2018  1391  1  5  0

    Using simple RPC service

    Use simple rpc script to call RPC service on small IOT devices
    <html>
    <head>
    	<script src="simple_rpc_service.js"></script>
    </head>
    <body onLoad='startup();'>
    <h4 id="hostname"> </h4>
    <p>Hello, see <a target="_blank" href="/rpc/Config.Get">rpc</a>
    <br><a target="_blank" href="/rpc/clearAll">clear strip</a>
    
    <p><table>
      <tr><td>Pin</td> <td><input type="number" id="GPIO.pin" value='2'/></td></tr>
      <tr><td>Red</td><td><input type="range" id="rval" name="rval" min="0" max="255" value='0' onchange="setPixel()"/></td></tr>
      <tr><td>Green</td><td><input type="range" id="gval" name="gval" min="0" max="255" value='0' onchange="setPixel()"/></td></tr>
      <tr><td>Blue</td><td><input type="range" id="bval" name="bval" min="0" max="255" value='0' onchange="setPixel()"/></td></tr>
    </table>
    <p><button href="#" id="setPixel" onclick="setPixel()">Set Pixel</button>
    <button href="#" id="clearAll" onclick="callRPCService('clearAll')">Clear All Pixel</button>
    <p><button href="#" id="setPixel" onclick="rebootDevice()">Reboot</button>
    
    <script>
    
      var log = function(msg) {
        console.log(msg);
      };
      log('Starting ...');
      function setPixel() {
        log("setPixel...");
      	var pin = parseInt(document.getElementById("GPIO.pin").value);
      	var rv = parseInt(document.getElementById("rval").value);
      	var gv = parseInt(document.getElementById("gval").value);
      	var bv = parseInt(document.getElementById("bval").value);
    	callRPCService('setPixel',{px:pin, r:rv, g:gv, b:bv});
      };
    </script>
    
    </body>
    </html>
    

    external by VimalRaj Selvam modified Feb 6, 2018  9  0  1  0

    Simple mongoose db

    Simple mongoose db: database.js
    const { Mongoose } = require('mongoose');
    
    let connection = null;
    
    const connectToDB = async () => {
      const mongoose = new Mongoose();
      mongoose.Promise = global.Promise;
    
      let mongoUserCredentials = '';
      if (process.env.MONGO_USER && process.env.MONGO_PASSWORD) {
        mongoUserCredentials = `${process.env.MONGO_USER}:${process.env.MONGO_PASSWORD}@`;
      }
    
      const MONGO_URL = process.env.MONGO_URL || 'localhost:27017';
      const DB_NAME = process.env.MONGO_DB_NAME || 'sample-db';
      const MONGO_CONNECTION_STRING = `mongodb://${mongoUserCredentials}${MONGO_URL}/${DB_NAME}`;
    
      await mongoose.connect(MONGO_CONNECTION_STRING);
      connection = mongoose;
    };
    
    const getDB = () => {
      if (!connection) {
        throw new Error('Call connectToDB first');
      }
      return connection;
    };
    
    module.exports = {
      connectToDB,
      getDB,
    };
    
    

    external by bludnic modified Jan 25, 2018  9  0  1  0

    Multilingual schema mongoose plugin

    Multilingual schema mongoose plugin: i18n.js
    import mongoose from 'mongoose'
    import traverse from 'traverse'
    
    const bodyToLocalized = (body, fields, lang = 'en') => {
      fields.forEach(field => {
        if (field in body) {
          body[field + '.' + lang] = body[field]
          delete body[field]
        }
      })
      return body
    }
    
    const localizedToBody = (body, fields, lang = 'en') => {
      fields.forEach(field => {
        if (field in body) {
          if (lang in body[field]) {
            body[field] = body[field][lang]
          } else {
            body[field] = '' // ?? if array?
          }
        }
      })
      return body
    }
    
    const toLocalized = (obj, lang) => {
      traverse(obj).forEach(function (item) {
        if (this.key === lang) {
          this.parent.update(item)
        }
      })
      return obj
    }
    
    const toLocalized2 = (obj, fields, lang) => {
      console.log('paths', traverse(obj).paths())
    }
    
    const I18n = (Schema, options) => {
    
      const i18nObject = (languages) => {
        let obj = {}
    
        languages.map(lang => obj[lang] = String)
    
        return obj
      }
    
      const megaMap = (Schema, startPath = '') => {
        Schema.eachPath((path, schema) => {
    
          if (schema instanceof mongoose.Schema.Types.DocumentArray) {
            if (schema.options.i18n) {
              delete schema.options.i18n
              Schema.remove(path)
    
              let langObject = {}
              options.languages.map(lang => {
                langObject[lang] = schema.options
              })
    
              Schema.add({ [path]: langObject })
            } else {
              megaMap(schema.schema, path)
            }
          } else if (schema instanceof mongoose.Schema.Types.Array) {
            //console.log(path, 'Array')
          } else if (schema instanceof mongoose.Schema.Types.String) {
            //console.log(path, 'String')
            if (schema.options.i18n) {
              //let fullPath = (startPath) ? startPath + '.' + path : path
              //console.log(fullPath, 'String', 'i18n')
              //console.log('pathname:options', Schema.paths[path].options)
              delete schema.options.i18n
    
              Schema.remove(path)
              Schema.add({
                [path]: i18nObject(options.languages)
              })
              //console.log('path', path);
    
            }
          } else if (schema instanceof mongoose.Schema.Types.Number) {
            //console.log(path, 'Number')
          } else if (schema instanceof mongoose.Schema.Types.Date) {
            //console.log(path, 'Date')
          } else {
            //console.log(path, 'Other')
          }
        })
      }
    
      const setLang = (Obj, key, lang = 'en') => {
        if (Array.isArray(Obj)) {
          Obj.map((key) => setLang(Obj[key], key, lang))
        } else if (typeof Obj === 'object') {
          //Object.keys(Obj).map((key) => setLang(Obj[key], key, lang))
          console.log(Obj[lang], key)
        }
      }
    
      megaMap(Schema)
    
      // setLang(Schema, 'ru')
    
      //console.log(Schema.paths);
    
      Schema.methods.toJSONLocalized = function() {
        setLang(this, null, 'en')
        console.log(this);
      }
    
      //console.log('obj', Schema.paths.included.schema.paths);
    }
    
    export {
      I18n,
      toLocalized,
      toLocalized2,
      bodyToLocalized,
      localizedToBody
    }
    
    

    external by t-raku modified Feb 22, 2018  8  0  1  0

    a usecase of processing all documents from mongo for each time getting a document ( using mongoose )

    a usecase of processing all documents from mongo for each time getting a document ( using mongoose ): mongoose.find.cursor.usecase.js
    let collection = mongoose.connection.collection(collectionName);
    let cursor = await collection.find();
    
    while( await cursor.hasNext() ){
      let document = cursor.next();
    };
    
    
    
    

    external by Igor-Lopes modified Feb 2, 2018  7  0  1  0

    Add timestamps and expiration to mongoose schema

    Add timestamps and expiration to mongoose schema: mongoose-timestamps.js
    var schema = mongoose.Schema({
        email: {
            type: String,
            required: true,
            lowercase: true,
            index: {
              unique: true
            }
          },
        expireAt: {
          type: Date,
          /* Defaults 7 days from now */
          default: new Date(new Date().valueOf() + 604800000),
          /* Remove doc 60 seconds after specified date */
          expires: 60
        }
        /* Automatically add createdAt and updatedAt fields to schema */
      }, { timestamps: true })
    
    

    external by xuyanbo03 modified Jan 26, 2018  4  0  1  0

    express and mongoose template

    express and mongoose template: gistfile1.txt
    const express=require("express")
    const mongoose=require("mongoose")
    //连接MongoDB数据库集合
    const DB_URL='mongodb://localhost:27017/app'
    mongoose.connect(DB_URL)
    mongoose.connection.on('connected',function(){
        console.log('mongo connect success')
    })
    //建文档、字段
    const User=mongoose.model('user',new mongoose.Schema({
        user:{
            type:String,
            require:true
        },
        age:{
            type:Number,
            require:true
        }
    }))
    //新增数据
    // User.create({
    //     user:'app',
    //     age:18
    // },function(err,doc){
    //     if(!err){
    //         console.log(doc)
    //     }else{
    //         console.log(err)
    //     }
    // })
    //删除数据
    // User.remove({user:'app'},function(err,doc){
    //     if(!err){
    //         console.log(doc)
    //     }else{
    //         console.log(err)
    //     }
    // })
    //更新数据
    // User.update({user:'app'},{'$set':{age:20}},function(err,doc){
    //     if(!err){
    //         console.log(doc)
    //     }else{
    //         console.log(err)
    //     }
    // })
    //新建app
    const app=express();
    const PORT=6666
    app.get('/',function(req,res){
        res.send('<h1>Hello World</h1>')
    })
    app.get('/data',function(req,res){
        User.findOne({user:'app'},function(err,doc){
            res.json(doc)
        })
        //res.json({name:'app',type:'IT'})
    })
    app.listen(PORT,function(){
        console.log('Node app start at port '+PORT)
    })
    
    

    external by Venelin Valkov modified Dec 18, 2014  229  0  3  0

    Wire up co, hapi, mongoose and node 0.11.9+ --harmony

    Wire up co, hapi, mongoose and node 0.11.9+ --harmony: Co Hapi Mongoose Generator Wiring.js
    var Mongoose = require('mongoose')
    var Hapi = require('hapi')
    var Co = require('co')
    
    Mongoose.connect('mongodb://localhost/mytestdb')
    
    var userSchema = Mongoose.Schema({
        name: String
    })
    
    var User = Mongoose.model('User', userSchema)
    
    var server = new Hapi.Server();
    server.connection({ 
        host: 'localhost', 
        port: 8000 
    });
    
    server.route({
        method: 'GET',
        path:'/hello', 
        handler: function(request, reply) {
    
            var wrapper = Co.wrap(function* (request, reply) {
                var user = new User({name: "John"})
                var newUser = yield user.save()
                var users = yield User.find().exec()
                reply([newUser, users])
            })
    
            wrapper(request, reply)
        }
    });
    
    server.start()
    
    

    external by masahirompp modified Dec 20, 2014  11955  94  4  0

    mongoose + typescript

    mongoose + typescript: User.ts
    /// <reference path="../tsd/tsd.d.ts" />
    
    import mongoose = require('mongoose');
    import passport = require('passport');
    
    interface IUser extends mongoose.Document {
      provider: string;
      id: string;
      authorId: string;
      displayName: string;
      emails: any;
      photos: any;
      show: boolean;
      created: Date;
      updated: Date;
    }
    
    /**
     * MongooseSchema
     * @type {"mongoose".Schema}
     * @private
     */
    var _schema: mongoose.Schema = new mongoose.Schema({
        provider: {
          type: String,
          require: true
        },
        id: {
          type: String,
          require: true
        },
        authorId: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'Author'
        },
        displayName: {
          type: String
        },
        emails: {
          type: mongoose.Schema.Types.Mixed
        },
        photos: {
          type: mongoose.Schema.Types.Mixed
        },
        show: Boolean,
        created: {
          type: Date,
          default: Date.now
        },
        updated: {
          type: Date,
          default: Date.now
        }
      })
      .pre('save', function(next) {
        this.updated = new Date();
        next();
      });
    
    /**
     * Mongoose.Model
     * @type {Model<IUser>}
     * @private
     */
    var _model = mongoose.model < IUser > ('User', _schema);
    
    class User {
    
      /**
       * static ユーザが存在しなければ作成して返す。
       * @param passport.Profile
       * @returns {Promise<User>}
       */
      static findOrCreate(profile: passport.Profile): Promise < User > {
        return new Promise < IUser > ((resolve, reject) => {
          _model.findOne({
              provider: profile.provider,
              id: profile.id
            })
            .exec()
            .then(user => {
              if (user) {
                return resolve(new User(user));
              }
              _model.create({
                  provider: profile.provider,
                  id: profile.id,
                  displayName: profile.displayName,
                  emails: profile.emails,
                  photos: profile.photos
                })
                .onResolve((err, user) => {
                  err ? reject(err) : resolve(new User(user));
                });
            });
        });
      }
    
      /**
       * static idからUserオブジェクトを取得
       * @param id
       * @returns {Promise<User>}
       */
      static findById(id: string): Promise < User > {
        return new Promise < IUser > ((resolve, reject) => {
          _model.findById(id)
            .exec()
            .onResolve((err, user) => {
              err ? reject(err) : resolve(new User(user));
            });
        })
      }
    
      /**
       * インスタンス変数
       */
      private _document: IUser;
    
      /**
       * コンストラクタ
       * @param mongoose.Document<IUser>
       */
      constructor(document: IUser) {
        this._document = document;
      }
    
      get provider(): string {
        return this._document.provider;
      }
    
      get image(): string {
        if (Array.isArray(this._document.photos)) {
          return this._document.photos.length > 0 ? this._document.photos[0] : null;
        }
        return this._document.photos;
      }
    
      get show(): boolean {
        return this._document.show;
      }
    
      get authorId(): string {
        return this._document.authorId;
      }
    }
    
    export = User;
    
    

    external by Chertpong modified Feb 22, 2016  182  0  2  0

    Mongoose simple model

    Mongoose simple model : course.js
    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    mongoose.Promise = require('bluebird');
    
    var courseSchema = new Schema({
        name:{ type : String, unique : true },
        description:{ type : String},
        tags:[
            { type : String }
        ],
        price : { type: Number }
    });
    
    var Course = mongoose.model('Course', courseSchema ,'Courses');
    
    module.exports = Course;
    
    
    • Public Snippets
    • Channels Snippets