1.创建服务器
const http = require('http');
//创建服务器
const app = http.createServer();
//为服务器对象添加请求事件
app.on('request', (req, res) => {
res.end('ok')
})
//监听端口
app.listen(3000);
2.链接数据库
const mongoose = require('mongoose');
//27017 数据库链接,一般在connect的第二个参数里要添加一个对象参数
mongoose.connect('mongodb://localhost/education')
.then(() => console.log('数据库连接成功'))
.catch(() => console.log('数据库连接失败'))
成功后:
3.创建用户集合
a. 需要创建Schema构造函数
//创建用户集合规则
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 2,
maxlength: 20
},
age: {
type: Number,
min: 3,
max: 130
},
password: String,
email: String,
hobbies: [ String ]
})
创建集合,往后的增删改查都依赖这个构造函数
//创建集合,返回的是集合构造函数
const User = mongoose.model('User', userSchema);
b. 创建文档:(有两种方式)
//创建文档
const user = new User({
name: '刘宇',
age: 22,
password: '12345678',
email: '2725891726@qq.com',
hobbies: ['数据结构','计算机导论']
})
//将文档插入数据库中
user.save()
第二种创建文档的方式:
//第一个参数是向集合当中插入的文档,第二个参数是回调函数
//回调函数中又有两个参数(err, result)result是插入文档的数据
User.create({name: '大哥',age: 22,password: '12345678',email: '277jp@qq.com',hobbies: ['数据结构','计算机导论']}, (err, result) => {
console.log(err)
console.log(result)
})
结果:
关于数据库的所有操作都是异步操作,所以create函数也返回的是promise对象即另一种写法:
User.create({name: '大海',age: 22,password: '12345678',email: '277lujing@qq.com',hobbies: ['数据结构','计算机导论']})
.then(result => {
console.log(result)
})
.catch(err => {
console.log(err)
})
结果:
关于如何创建文档,如果现成的JSON文件,可以使用命令直接进行导入:
mongoimport -d 数据库名称 -c 集合名称 --file ./文档集合名称.json
完整代码:
//app.js 中的代码
//搭建网站服务器
//链接数据库,创建用户集合
//实现增删改查
const http = require('http');
const mongoose = require('mongoose');
//27017 数据库链接,一般在connect的第二个参数里要添加一个对象参数
mongoose.connect('mongodb://localhost/education')
.then(() => console.log('数据库连接成功'))
.catch(() => console.log('数据库连接失败'))
//创建用户集合规则
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 2,
maxlength: 20
},
age: {
type: Number,
min: 3,
max: 130
},
password: String,
email: String,
hobbies: [ String ]
})
//创建集合,返回的是集合构造函数
const User = mongoose.model('User', userSchema);
// //创建文档
// const user = new User({
// name: '刘宇',
// age: 22,
// password: '12345678',
// email: '2725891726@qq.com',
// hobbies: ['数据结构','计算机导论']
// })
// //将文档插入数据库中
// user.save()
//第一个参数是向集合当中插入的文档,第二个参数是回调函数
//回调函数中又有两个参数(err, result)result是插入文档的数据
// User.create({name: '卢静',age: 22,password: '12345678',
// email: '277lujing@qq.com',hobbies: ['数据结构','计算机导论']}, (err, result) => {
// console.log(err)
// console.log(result)
// })
User.create({name: '大海',age: 22,password: '12345678',email: '277lujing@qq.com',hobbies: ['数据结构','计算机导论']})
.then(result => {
console.log(result)
})
.catch(err => {
console.log(err)
})
//创建服务器
const app = http.createServer();
//为服务器对象添加请求事件
app.on('request', (req, res) => {
res.end('ok')
})
//监听端口
app.listen(3000);