Created
November 18, 2014 08:39
-
-
Save wohugb/a1ea7b4589742dda607f to your computer and use it in GitHub Desktop.
how to use koa.js+mongoose 如何使用?
This file contains 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
var koa = require('koa') | |
, mongoose = require('mongoose') | |
, Blog = require('./models/blog') | |
; | |
//连接数据库 | |
var uris = 'mongodb://192.168.1.2/db,mongodb://192.168.1.3/db'; | |
var options = { | |
db: { native_parser: true }, | |
server: {'auto_reconnect': true,'poolSize': 10}, | |
replset: {readPreference: 'nearest',strategy: 'ping',rs_name: 'myReplSet'}, | |
}; | |
mongoose.connect(uris,options); | |
//路由 | |
app.get('/', function *(){ | |
var blogs = yield Blog.find().exec(); | |
yield this.render('blog', {blogs: blogs}); | |
}) | |
app.listen(8317); |
This file contains 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
'use strict'; | |
var mongoose = require('mongoose'), | |
Schema = mongoose.Schema; | |
var BlogSchema = new Schema({ | |
title:{ | |
type:String, | |
required: '标题为空!' | |
} | |
}); | |
BlogSchema.set('toJSON', { | |
getters: true, | |
virtuals: true, | |
transform: function(doc, ret, options) { | |
options.hide = options.hide || '_id __v'; | |
if (options.hide) { | |
options.hide.split(' ').forEach(function (prop) { | |
delete ret[prop]; | |
}); | |
} | |
} | |
}); | |
module.exports = mongoose.model('Blog', BlogSchema); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment