1.mongoose默认参数

  1. var UserSchema = new mongoose.Schema({
  2. name:String,
  3. age:Number,
  4. status:{
  5. type: Number,
  6. default:1
  7. }
  8. })

2.模块化

  1. //model/db.js
  2. const mongoose = require('mongoose');
  3. mongoose.connect( 'mongodb://127.0.0.1:27017/eggcms', {useNewUrlParser: true},(err)=>{
  4. if(err) throw err;
  5. console.log("database连接成功")
  6. });
  7. module.exports = mongoose;
  1. //model/user.js
  2. var mongoose = require('./db');
  3. var UserSchema = new mongoose.Schema({
  4. name:String,
  5. age:Number
  6. })
  7. var User = mongoose.model('User',UserSchema,'user');
  8. module.exports = User;
  1. //app.js引入
  2. const UserModel = require('./model/user');
  3. UserModel.find({},(err,doc)=>{
  4. console.log(doc)
  5. })

3.console.time测试mongoose的性能

  1. console.time('user')
  2. const UserModel = require('./model/user');
  3. console.timeEnd('user')
  4. console.time('news')
  5. const NewsModel = require('./model/news');
  6. console.timeEnd('news')