Skip to content

Instantly share code, notes, and snippets.

@shokai
Created August 1, 2012 17:32
Show Gist options
  • Save shokai/3229076 to your computer and use it in GitHub Desktop.
Save shokai/3229076 to your computer and use it in GitHub Desktop.
mongoose virtual attributes
// http://mongoosejs.com/docs/virtuals.html
// npm install mongoose underscore
var _ = require('underscore');
var mongoose = require('mongoose');
mongoose.connect(process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/test', function(err){
if(err){
console.error(err);
process.exit(1);
}
});
var Schema = mongoose.Schema, ObjectId = Schema.ObjectId;
var RecipeSchema = new Schema({
id : {type: String, unique: true},
title : {type: String},
created_at : {type: Date, default: Date.now}
});
RecipeSchema.virtual('url').get(function(){
return 'http://shokai.org/'+this.id;
});
var Recipe = mongoose.model('Recipe', RecipeSchema);
Recipe.latests = function(num){
return this.find().sort('created_at', -1).limit(num);
};
var recipe = new Recipe({id: '29jg', title: '肉じゃが'});
recipe.save();
Recipe.latests(3).exec(function(err, docs){
if(err){
throw err;
}
else{
_.each(docs, function(doc){
console.log(doc.url);
});
}
mongoose.disconnect();
});
% node mongoose_virtual_attr.js
http://shokai.org/29jg
@JacksonTian
Copy link

how about the performence?

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