working on it ...

Filters

Explore Public Snippets

Sort by

Found 381 snippets matching: mongoose

    public by tomsim  1474  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  1447  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  13  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 t-raku  11  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  10  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 bludnic  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 xuyanbo03  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 NikitaBogdanov  3  0  1  0

    Mongoose find with regex

    Mongoose find with regex: city.js
    exports.findCities = (req, res) => {
      let param = m.getBody(req);
      models.city.find({title: new RegExp('^' + param.title, 'i'), region: new RegExp(param.region, 'i')})
        .limit(25)
        .exec(function (err, data) {
          if (err) {
            return m.ecb(res, 403, 'Something went wrong')
          }
          res.send(data)
        })
    };
    
    

    external by deresegetachew  2  0  1  0

    sendInvitation: showcasing using mongoose . The Transaction considers the success of send email message to Rabbit

    sendInvitation: showcasing using mongoose . The Transaction considers the success of send email message to Rabbit: sendInvitation.js
    const sendInvitation = async (parent, { invite }, ctx, info) => {
      try {
        const blackListEmail = req.user.email;
    
        await isInviteToSendValid(invite, blackListEmail);
      } catch (err) {
        return formatYupError(err);
      }
    
      let { companyName, email, message } = invite;
    
      //check if an invitation is already sent
      const db_session = await global.dbConnection.startSession();
    
      db_session.startTransaction();
    
      try {
        let inviteToSave = {
          companyName: invite.companyName,
          message: invite.message,
          email: invite.email,
          status: 'Pending',
          dateModified: moment().format('MMM DD YY')
        };
    
        let invitingCompany = await Company.find({
          _id: ObjectId(req.user.company)
        })
          .select(
            'invitations businessType businessArea companyIsVerified country companyName myAgents myImporters myVendors image'
          )
          .session(db_session)
          .exec();
    
        if (invitingCompany) {
          let existingInvitation = find(invitingCompany.invitations, function(
            invite
          ) {
            return String(invite.email) == String(email);
          });
    
          if (existingInvitation) {
            if (
              existingInvitation.status == 'Confirmed' ||
              existingInvitation.status == 'Cancelled'
            ) {
              await db_session.abortTransaction();
              return [
                errors.inviteAlreadyCancelledOrConfirmed({
                  companyName: existingInvitation.companyName,
                  status: existingInvitation.status
                })
              ];
            } else {
              existingInvitation.dateModified = moment().format('MMM DD YY');
            }
          } else {
            //new Invitation
            invitingCompany.invitations.push(inviteToSave);
          }
        } else {
          await db_session.abortTransaction();
          return [errors.errorSendingInvitation()];
        }
    
        let save_invitation = await invitingCompany.save({ session: db_session });
        if (!save_invitation) {
          await db_session.abortTransaction();
          return [errors.errorSendingInvitation()];
        } else {
          //send email and commit the transaction.
          let a =
            base_url_web + `register/invite/${companyId}/${inviteToSave.email}`;
          let accept_a =
            base_url_web +
            `register/existing/${invitingCompany._id}/${inviteToSave.email}/accept`;
          let decline_a =
            base_url_web +
            `register/existing/${invitingCompany._id}/${inviteToSave.email}/decline`;
          let companyLogo = invitingCompany.image;
          let rfpiCount = 0;
          let piCount = 0;
    
          if (invitingCompany.businessType == 'Importer') {
            rfpiCount = await PI.countDocuments({ importerId: req.user.company });
            piCount = await PI.countDocuments({
              importerId: req.user.company,
              status: { $eq: 'Converted to PI' }
            });
          } else if (invitingCompany.businessType == 'Exporter') {
            rfpiCount = await PI.countDocuments({ vendorId: req.user.company });
            piCount = await PI.countDocuments({
              vendorId: req.user.company,
              status: { $eq: 'Converted to PI' }
            });
          }
    
          let payload = {
            email: inviteToSave.email,
            subject: `Invitation to join or Connect on LightTrading Platform`,
            invited: inviteToSave.companyName,
            inviter: invitingCompany.companyName,
            inviterBussType: invitingCompany.businessType,
            inviterBussArea: invitingCompany.businessArea,
            inviterConnections:
              invitingCompany.myAgents.length +
              invitingCompany.myVendors.length +
              invitingCompany.myImporters.length,
            inviterRFPI: rfpiCount,
            inviterPI: piCount,
            inviterCompletedOrder: 0,
            inviterReview: 0,
            inviterVerified: invitingCompany.companyIsVerified,
            inviterBussCountry: invitingCompany.country,
            message: inviteToSave.message,
            logo: companyLogo,
            link: a,
            link_accept: accept_a,
            link_decline: decline_a,
            eventId: new mongoose.mongo.ObjectId(),
            dateCreated: moment(),
            eventType: eventTypeEnums.invitationSent,
            actionUrl: '',
            summary: `Invitation sent to ${inviteToSave.companyName} to connect on light trading.`
          };
    
          let paramRabbit = {
            chanelName: ltChanel.chanelName,
            exchange: eventTypeEnums.invitationSent, //event name
            routingKey:
              eventTypeEnums.invitationSent +
              '.' +
              invitingCompany._id.toString() +
              '.*'
          };
    
          let send_email = await publishToRabbit(
            paramRabbit,
            new Buffer(JSON.stringify(payload)),
            { persistent: true }
          );
          if (send_email) {
            await db_session.commitTransaction();
            return inviteToSave;
          } else {
            await db_session.abortTransaction();
            return [errors.errorSendingInvitation()];
          }
        }
      } catch (e) {
        await db_session.abortTransaction();
        await db_session.endSession();
    
        throw e.message;
      } finally {
        await db_session.endSession();
      }
    };
    
    

    external by Venelin Valkov  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()
    
    
    • Public Snippets
    • Channels Snippets