增删改查操作
和数据库相关的所有操作都是异步操作
增

// 引入MongoDB
const mongoose = require('mongoose')
// 如果后面插入数据 发现没有该数据库 会自动创建
mongoose.connect('mongodb://localhost/playground', {
useUnifiedTopology: true,
useNewUrlParser: true
})
.then(() => console.log("数据库连接成功"))
.catch(() => console.log(err, '数据库连接失败'))
// 设定集合规则
const courseSchema = new mongoose.Schema({
name: String,
author: String,
isPublic: Boolean
})
// 使用规则创建集合
// 返回一个构造函数
// 参数
// 集合名称
// 集合规则
const Course = mongoose.model('Course', courseSchema)
/* Course.create({
name: 'xiaonao',
author: 'gg',
isPublic: false
}, (err, result) => {
// 错误对象
console.log(err)
// 当前插入的文档
console.log(result)
}) */
Course.create({
name: 'xiao',
author: 'gg',
isPublic: false
})
.then(result => {
console.log(result)
})
将文件中的全部数据快速传入数据库中
在命令行工具中输入:
mongoimport -d playground -c users --file ./user.json

查

// 引入MongoDB
const mongoose = require('mongoose')
// 如果后面插入数据 发现没有该数据库 会自动创建
mongoose.connect('mongodb://localhost/playground', {
useUnifiedTopology: true,

最低0.47元/天 解锁文章
952

被折叠的 条评论
为什么被折叠?



