Giter Club home page Giter Club logo

mongoose-random's Introduction

mongoose-random buildstatus

Fetch random document(s) from your mongoose collections.

Installation

npm install mongoose-random

Usage

var mongoose = require('mongoose');
var random = require('mongoose-random');

var Schema = new mongoose.Schema({ /* ... */ });
Schema.plugin(random, { path: 'r' }); // by default `path` is `random`. It's used internally to store a random value on each doc.

var Song = mongoose.model('Song', Schema);

// get 10 random songs
Song.findRandom().limit(10).exec(function (err, songs) {
  console.log(songs);
});

// `findRandom` has the same signature as mongoose's `Model.find`:
var filter = { playlist: { $in: ['hip-hop', 'rap'] } };
var fields = { name: 1, description: 0 };
var options = { skip: 10, limit: 10 }
Song.findRandom(filter, fields, options, function (err, songs) {
  console.log(songs);
});

// if you have an existing collection, it must first by synced.
// this will add random data for the `path` key for each doc.
Song.syncRandom(function (err, result) {
  console.log(result.updated);
});

License

The MIT License (MIT)

Copyright (c) 2013 Mihai Tomescu

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

mongoose-random's People

Contributors

matomesc avatar switz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

mongoose-random's Issues

Support for .snapshot()

This was my original query I wanted

model_user
    .findRandom({ 'key.61' : { $exists : false } })
    .limit(10)
    .snapshot(true)
    .stream()
    .on('data', function(data) {
      beAwesome()
    })
    .on('err', function(err) {
      console.log(err);
    })

.snapshot(true) does not seem to be supported. When this is present, the following error occurs:
planner returned error: unable to find index for $geoNear query

syncRandom fail silently.

I am using mongoose 4.11 and syncRandom just fails silently. the callback never fires inside so I don't know what is happening with it.

syncRandom() throwing validation error

Error below:

ValidationError: user validation failed
    at MongooseError.ValidationError (/home/vagrant/local/venvy-eva/node_modules/mongoose/lib/error/validation.js:22:11)
    at model.Document.invalidate (/home/vagrant/local/venvy-eva/node_modules/mongoose/lib/document.js:1355:32)
    at init (/home/vagrant/local/venvy-eva/node_modules/mongoose/lib/document.js:337:18)
    at init (/home/vagrant/local/venvy-eva/node_modules/mongoose/lib/document.js:328:7)
    at init (/home/vagrant/local/venvy-eva/node_modules/mongoose/lib/document.js:328:7)
    at model.Document.init (/home/vagrant/local/venvy-eva/node_modules/mongoose/lib/document.js:289:3)
...

Schema Declaration:

var userSchema =  new mongoose.Schema({ ... });
// For pulling random documents - https://github.com/matomesc/mongoose-random
userSchema.plugin(random, { path: 'r' });

var user    = mongoose.model('user', userSchema)

user.syncRandom(function (err, result) {
  if (err) return console.log(err);
  console.log(result.updated);
});

Any help is appreciated, thanks.

DeprecationWarning for Mongoose 4.5.0

The latest version of Mongoose is 4.11.11. When you use this code it gives a deprecation warning:

DeprecationWarning: Mongoose: Query.prototype.stream() is deprecated in mongoose >= 4.5.0, use Query.prototype.cursor() instead

syncRandom does not update only docs that are missing path

I read this from a reply to an earlier issue:

Essentially .syncRandom() should just query documents that are missing the random field and set it. Then you'd just run it once at the very start.

But looking at the code, syncRandom can calls self.find({}) instead of something like:

schema.statics.syncRandom = function(force, callback) {
  if ('function' === typeof force) {
    callback = force; force = false;
  }
  var query = {};
  if (!force) {
    query[path] = {$exists: false};
  }
  var stream = self.find(query).stream({ transform: transform });
  ...

I would like to call syncRandom() at the start of my server app without worrying about whether it unnecessarily resets path on a potentially huge set of docs.

CastError

Great little library! Any idea what might be causing this?

{ message: 'Cast to number failed for value "Point" at path "__QueryCasting__"',
  name: 'CastError',
  type: 'number',
  value: 'Point',
  path: '__QueryCasting__' }

It's definitely from line 28:

  query[path] = query[path] || {
    $near: {
      $geometry: { type: 'Point', coordinates: coords } // this one
    }
  };

Thanks!

That's really really is a hack way

I have read you source code.
I think return query object will better than return result directly, So I can do :

Song.findRandom().limit(10)

TypeError: <collection>.findRandom is not a function

                const rand = flashcard.findRandom().limit(1).exec(function (err, flashcard) {
                console.log(flashcard);
              });

This is how I am using the .findRandom() function, but I get an error stating that it's not a function. Not sure where I went wrong.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.