How to create a function using mongoose in nodejs

I have a general function in mongodb.

db.system.js.save({_id: "Apps",value : function (doc, targetCollection) {

    while (1) {

        var cursor = db.targetCollection.find( {}, { App_id: 1 } ).sort( { _id: -1 } ).limit(1);

        var seq = cursor.hasNext() ? cursor.next().App_id + 1 : 1;

        doc.App_id = seq;

        db.targetCollection.insert(doc);

        var err = db.getLastErrorObj();

        if( err && err.code ) {
            if( err.code == 11000 /* dup key */ )
                continue;
            else
                print( "unexpected error inserting data: " + tojson( err ) );
        }

        break;
    }
}
}); 

I need to save this function in mongodb using mongoose through nodejs.

Please help me to do this.

This is not possible with Mongoose by default.
You should try this package: https://npmjs.org/package/mongoose-function