1. 启动 Mongodb 数据库
-
在 Mongodb 的 bin 文件夹下打开控制台
-
输入 mongod.exe --dbpath D:\MongoDB\data\db 回车
-
重复步骤一,在控制台中输入 mongo.exe --port 27017
-
步骤三的服务可以按 ctrl C 停止,但步骤一的服务不能停止,是数据库的服务
2.nodejs连接mongodb
代码部分
// nodejs 连接 mongodb
// 体会 nodejs 连接 mongodb 的能力,不会真正的用到路由上
// mongoose 对接路由的功能
const MongoClient = require("mongodb").MongoClient // mongodb 客户端
// compass, 命令行, nodejs 都可以作为数据库的客户端
const url = 'mongodb://localhost:27017' // 本地启动的 mongodb 服务
const dbName = 'comment1' // 数据库(留言板项目的数据库)
MongoClient.connect(url, {
useUnifiedTopology: true,
useNewUrlParser: true
}, (err, client) => {
if (err) {
console.error('mongodb 连接出错', err)
return
}
console.log('mongodb 连接成功')
const db = client.db(dbName) // 切换数据库 命令行:use comment1
// 切换到指定的集合 collection
const userCollection = db.collection('users')
// 查询数据
userCollection.find().toArray((err, result) => {
if (err) {
console.error('查询数据出错', err)
return
}
console.log('查询结果', result)
})
// 关闭
// client.close()
})
带条件查询:
userCollection.find({ city: 'beijing', username: 'zhangsan' }).toArray()
排序:
1. userCollection.find().sort({ age: 1 }).toArray()
// -1为倒序
2. 按插入顺序排序:`sort({ _id: 1 })`
新增数据:
userCollection.insertOne({
username: 'liudehua',
password: 'abc',
age: 30,
city: 'xianggang'
}, (err, result) => {
if (err) {
console.error('查询数据出错', err)
return
}
console.log('插入后的返回结果', result)
})
修改数据:
userCollection.updateOne(
{ username: 'zhangsan' }, // 修改条件
{ $set: { age:22 , city: 'guangzhou'} }, // 修改内容
(err, result) => {
if (err) {
console.error('修改数据出错', err)
return
}
console.log('修改后的返回结果', result)
}
)
删除数据:
userCollection.deleteOne({ username: 'wangwu' }, (err, result) => {
if (err) {
console.error('删除数据出错', err)
return
}
console.log('删除成功')
}
)