Skip to content

Instantly share code, notes, and snippets.

@alonronin
Created May 9, 2013 02:19
Show Gist options
  • Save alonronin/5545119 to your computer and use it in GitHub Desktop.
Save alonronin/5545119 to your computer and use it in GitHub Desktop.
node.js mongoose random documents
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var schema = new mongoose.Schema({
name: String,
email: String,
random: {type: [Number], default: function(){ return [Math.random(), Math.random()]}, index: '2d'}
});
var model = mongoose.model('random', schema);
model.remove({}, function(){
var docs = ['some', 'names', 'to', 'insert', 'into', 'collection'].map(function(item){
return {
name: item,
email: item + '@' + 'nomail.com',
random: [Math.random(), Math.random()]
};
});
model.collection.insert(docs, function(err, result){
console.log('');
console.log('===> normal order <===');
console.log('');
console.log(result);
model
.find()
.where('random')
.near([Math.random(), Math.random()])
.exec(function(err, result){
console.log('');
console.log('===> random order <===');
console.log('');
console.log(result);
});
})
});
@victorkurauchi
Copy link

thanks for that man ! i was trying to do something like that. Helped a lot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment