package.json
{
"name": "test4",
"version": "0.1.0",
"private": true,
"scripts": {
"start": "node bin/www",
"dev": "./node_modules/.bin/nodemon bin/www",
"prd": "pm2 start bin/www",
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"debug": "^4.1.1",
"koa": "^2.7.0",
"koa-bodyparser": "^4.2.1",
"koa-convert": "^1.2.0",
"koa-json": "^2.0.2",
"koa-logger": "^3.2.0",
"koa-onerror": "^4.1.0",
"koa-router": "^7.4.0",
"koa-static": "^5.0.0",
"koa-views": "^6.2.0",
"mongoose": "^6.2.8",
"pug": "^2.0.3"
},
"devDependencies": {
"nodemon": "^1.19.1"
}
}
model.js
// 数据模型(规范数据格式)
const mongoose = require('./db')
// 定义schema(数据规范)
const UserSchema = mongoose.Schema({
username: {
type: String,
required: true, // 必填
unique: true // 唯一,不重复
},
password: String,
age: Number,
city: String,
gender: {
type: Number,
default: 0 // 设置默认值,0-保密,1-男,2-女
}
}, {
timestamps: true // 时间戳,自动添加文档的创建时间
})
// 定义Model
const User = mongoose.model('user', UserSchema)
module.exports = {
User
}
db.js
// 连接数据库(mongodb的服务端)
// 获取mongoose插件
const mongoose = require('mongoose');
const url = 'mongodb://localhost:27017';
const dbName = 'comment2'
// 连接数据库
mongoose.connect(`${url}/${dbName}`, {
useNewUrlParser: true,
useUnifiedTopology: true
});
// 获取当前的连接对象
const conn = mongoose.connection;
// 监听错误
conn.on('error', err => {
console.error('mongoose连接出错', err)
})
module.export = mongoose;
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星