Created
August 1, 2012 17:32
-
-
Save shokai/3229076 to your computer and use it in GitHub Desktop.
mongoose virtual attributes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% node mongoose_virtual_attr.js | |
http://shokai.org/29jg |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how about the performence?