主要涉及:
- 在Node.js中操作MongoDB
- MongoDB数据库和web服务的实际项目
Node.js 中操作MongoDB
参考:
在服务端操作 MongoDB:https://docs.mongodb.com/drivers/ 在 Node.js 中操作
MongoDB : https://docs.mongodb.com/drivers/node/
步骤:
- 初始化项目文件夹 mkdir node-mongodb-demo
- npm init -y
- npm i mongodb
- 连接mongodb数据库,创建index.js进行引入连接
- node执行index.js node index.js
index.js
const {
MongoClient } = require("mongodb");
// Connection URI
const uri =
"mongo://127.0.0.1:27017";
// Create a new MongoClient
const client = new MongoClient(uri);
async function run() {
try {
// Connect the client to the server
await client.connect();
// Establish and verify connection
await client.db("admin").command({
ping: 1 });
console.log("Connected successfully to server");
} catch (err) {
console.log('Connect failed')
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run()
Node对 MongoDB 进行 CRUD
CRUD(创建,读取,更新,删除)操作使您可以处理存储在MongoDB中的数据。
创建文档
插入一个:
const pizzaDocument = {
name: "Neapolitan pizza",
shape: "round",
toppings: [ "San Marzano tomatoes", "mozzarella di bufala cheese" ],
};
const result = await pizzaCollection.insertOne(pizzaDocument);
console.dir(result.insertedCount);
插入多个:
const pizzaDocuments = [
{
name: "Sicilian pizza", shape: "square" },
{
name: "New York pizza", shape: "round" },
{
name: "Grandma pizza", shape: "square" },
];
const result = pizzaCollection.insertMany(pizzaDocuments);
console.dir(result.insertedCount);
查询文档
const findResult = await orders.find({
name: "Lemony Snicket",
date: {
$gte: new Date(new Date().setHours(00, 00, 00)),
$lt: new Date(new Date().setHours(23, 59, 59)),
},
});
删除文档
const doc = {
pageViews: {
$gt: 10,
$lt: 32768
}
};
// 删除符合条件的单个文档
const deleteResult = await collection.deleteOne(doc);
console.dir(deleteResult.deletedCount);
// 删除符合条件的多个文档
const deleteManyResult = await collection.deleteMany(doc);
console.dir(deleteManyResult.deletedCount);
修改文档
更新1个文档:
const filter = {
_id: 465 };
// update the value of the 'z' field to 42
const updateDocument = {
$set: {
z: 42,
},
};
// 更新多个
const result = await collection.updateOne(filter, updateDocument);
// 更新多个
const result = await collection.updateMany(filter, updateDocument);
替换文档:
const filter = {
_id: 465 };
// replace the matched document with the replacement document
const replacementDocument = {
z: 42,
};
const result = await collection.replaceOne(filter, replacementDocument);
index.js
const {
MongoClient, ObjectID } = require('mongodb')
// ObjectID 在MongoDB中是一个类型,必须使用ObjectID包裹才能生效
const client = new MongoClient('mongodb://127.0.0.1:27017', {
useUnifiedTopology: true
}