mongoose模块化
为了方便开发和维护需要模块化,下边将具体演示
目录
model
db.js
user.js
news.js
test
user-find.js
news-find.js
db.js-连接数据库
const mongoose = require('mongoose');
mongoose.connect(
'mongodb://localhost:27017/dadi',
{useNewUrlParser: true, useUnifiedTopology: true},
(err, doc) => {
if (err) { console.log('err', err); return}
console.log('连接成功');
}
)
module.exports = mongoose;
user.js
const mongoose = require('./db');
const UserSchema = mongoose.Schema({
name: String,
age: Number,
status: {
type: String,
default: 1
}
})
module.exports = mongoose.model('User', UserSchema, 'users');
news.js
const mongoose = require('./db');
const NewsSchema = mongoose.Schema({
title: String,
author: {
type: String,
default: '玄空'
},
pic: String,
status: {
type: Number,
default: 1
}
})
module.exports = mongoose.model('New', NewsSchema, 'news')
使用
user-find.js
const NewsModel = require('../model/news')
NewsModel.find({}, (err, doc) => {
if(err){ console.log('err: ', err); return }
console.log('doc: ', doc);
})
运行
node test/user-find.js
user-create.js
const UserModel = require('../model/user')
const user =new UserModel({
name: 'zhangsan5',
age: 20
})
user.save((err, doc) => {
if(err) {
console.log('err: ', err);
return;
}
console.log('增加成功');
UserModel.find({}, (err, doc) => {
if(err){ console.log('err: ', err); return }
console.log('doc: ', doc);
})
})
news-find.js
const UserModel = require('../model/user')
UserModel.find({}, (err, doc) => {
if(err){ console.log('err: ', err); return }
console.log('doc: ', doc);
})
其他将不再举例
总结
方便使用和维护,db.js 连接数据库,model中定义schema和model,外部文件中调用model
性能测试
使用console.time来查看程序运行的性能。
console.time('user');
const UserModel = require('./model/user')
console.timeEnd('user');
console.time('news');
const NewsModel = require('./model/news')
console.timeEnd('news');
console.time('js');
for(i=0; i< 1000000000; i++) {
// 要运行2s
}
console.timeEnd('js');