一、默认参数
const mongoose = require('mongoose')
mongoose.connect(
'mongodb://127.0.0.1:27017/eggcms',
{ useUnifiedTopology: true, useNewUrlParser: true },
(err) => {
if (err) return console.log(err)
console.log('数据库连接成功')
}
)
// 定义Schema
var UserSchema = mongoose.Schema({
name: String,
age: Number,
status: {
type: Number,
default: 1 // 默认参数
}
})
// 定义model操作数据库
var UserSchema = mongoose.model('User', UserSchema, 'users')
// 增加数据(当不写status时,默认增加 status: 1 )
var User = new UserModel({
name: 'zs',
age: 18
})
User.save((err) => {
if (err) return console.log(err)
console.log('数据库连接成功')
})
二、模块化
1.在根目录下新建文件夹model,然后在model中新建db.js
/* db.js */
var mongoose = require('mongoose')
mongoose.connect(
'mongodb://127.0.0.1:27017/eggcms',
{ useUnifiedTopology: true, useNewUrlParser: true },
(err) => {
if (err) return console.log(err)
console.log('数据库连接成功')
}
)
module.exports = mongoose
2.在model中新建user.js
/* user.js */
var mongoose = require('mongoose')
var UserSchema = mongoose.Schema({
name: String,
age: Number,
status: {
type: Number,
default: 1 // 默认参数
}
})
module.exports = mongoose.model('User', UserSchema, 'users')
3.在model中再新建一个news.js
/* news.js */
var mongoose = require('mongoose')
var NewsSchema = mongoose.Schema({
title: String,
author: String,
pic: String,
content: String,
status: {
type: Number,
default: 1 // 默认参数
}
})
module.exports = mongoose.model('News', NewsSchema, 'news')
4.在app.js中引入user.js与news.js,并且操作数据库
/* app.js */
var UserModel = require('./model/user')
var NewsModel = require('./model/news')
// 查询用户信息
UserModel.find({}, (err, res) => {
if (err) return console.log(err)
console.log(res)
})
// 新增新闻
var news = new NewsModel({
title: '我是标题',
author: '尼古拉斯',
pic: '123.png',
content: '我是新闻的内容'
})
news.save((err) => {
if (err) return console.log(err)
console.log('新增成功')
})