Skip to content

Instantly share code, notes, and snippets.

@topliceanu
Created October 14, 2011 16:55
Show Gist options
  • Save topliceanu/1287659 to your computer and use it in GitHub Desktop.
Save topliceanu/1287659 to your computer and use it in GitHub Desktop.
mongoose problems
//deps
var mongoose = require( 'mongoose' );
var Schema = mongoose.Schema;
var ObjectId = mongoose.Schema.ObjectId;
//config
var mongo = require( './../conf.js' ).mongo ;
mongo.database = 'learn';
//connect to mongo
var connString = 'mongodb://'+mongo.host+':'+mongo.port+'/'+mongo.database ;
var conn = mongoose.connect( connString );
//recursive embedded-document schema
var Comment = new Schema();
Comment.add({
title: { type: String, index: true },
date: Date,
body: String,
comments: [Comment]
});
var BlogPost = new Schema({
title: { type: String, index: true, unique: true },
slug: { type: String, lowercase: true, trim: true },
date: { type: Date, default: Date.now },
buf: Buffer,
comments: [Comment],
creator: Schema.ObjectId
});
var Person = new Schema({
name: {
first: String,
last: String
},
email: { type: String, required: true, index: {unique: true, sparse: true } },
alive: Boolean
});
// accessing a schema type by key - !! NOT really working
BlogPost
.path( 'date' )
.default( function(){
return new Date();
})
.set( function(v){
return v === 'now' ? new Date() : v ;
});
// pre hook
var emailAuthor = function( done ){
console.log( '\nemailing author!\n' );
done();
};
BlogPost.pre( 'save', function( next, done ){
//next( new Error('something went wrong') );
next();
});
BlogPost.pre( 'save', function( next, done ){
//use done() to call stuff from async functions
emailAuthor( done );
next();
});
//methods
BlogPost.methods.findCreator = function( callback ){
return this.db.model( 'Person' )
.findById( this.creator, callback );
};
BlogPost.statics.findByTitle = function( title, callback ){
return this.find({ title: title }, callback );
};
BlogPost.methods.expressiveQuery = function( creator, date, callback ){
return this
.find( 'creator', creator )
.where( 'data' )
.gte( date )
.run( callback );
};
//plugin
var slugGenerator = function( options ){
options = options || {};
var key = options.key || 'title';
return function slugGenerator( schema ){
schema.path( key ).set( function( v ){
this.slug = v
.toLowerCase()
.replace( /[^a-z0-9]/g, '' )
.replace( /-+/g, '' );
return v ;
});
};
};
BlogPost.plugin( slugGenerator() );
//define models
mongoose.model( 'BlogPost', BlogPost );
mongoose.model( 'Person', Person );
//tests
var BlogPostModel = mongoose.model( 'BlogPost' );
var instance = new BlogPostModel();
instance.title = 'alex' ;
instance.save( function( err ){
console.log( 'run save callback' );
// only use this in case of an error
if( err ) {
console.log( 'there was an error' );
}
else{
console.log( 'no error' );
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment