nodejs下使用mongoDB

186 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 1 天,点击查看活动详情

引言

nodejs作为一门非常火爆的技术栈,可以做很多事情,那么nodejs和MongoDB碰撞在一起又会产生怎么样的火花呢?接下来我们就来了解一下,在Nodejs下使用MongoDB。

MongoDB的优点

先看一下MongoDB的优点:

MongoDB有以下一些优点:

  • 文档数据模型:MongoDB使用文档数据模型,允许存储任意结构的数据,并允许在同一集合中的文档具有不同的结构。
  • 高性能:MongoDB使用内存映射文件和分片技术来提高数据库性能,并且支持水平扩展以扩展处理能力。
  • 简单易用:MongoDB提供简单易用的API,易于开发和维护。
  • 容错:MongoDB提供冗余和自动故障转移功能,以保护数据不丢失。
  • 跨平台:MongoDB可在各种操作系统平台上运行,并且支持多种编程语言。
  • 开源:MongoDB是一个开源软件,拥有广泛的社区支持和生态系统。

总体而言,MongoDB是一个功能强大,易于使用的NoSQL数据库,适用于各种类型的大规模数据存储需求。

开启我们的配置

使用Node.js操作MongoDB,需要使用MongoDB驱动程序。常用的驱动程序是MongoDB Native。安装它的命令是:

npm install mongodb

在使用之前,需要连接到MongoDB数据库。

我们可以做如下配置:

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<user>:<password>@cluster.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const collection = client.db("test").collection("devices");
  // perform actions on the collection object
  client.close();
});

连接后,可以使用数据库中的集合进行CRUD(创建,读取,更新,删除)操作。

开始我们的curd之旅吧。

下面是一个MongoDB的curd的例子,我们会使用Nodejs+MongoDB来完成一系列的增删改查的操作


const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<user>:<password>@cluster.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const db = client.db("test");
  const collection = db.collection("devices");

  // Create
  collection.insertOne({name: "Device 1"}, (error, result) => {
    console.log("Inserted a document into the collection");
  });

  // Read
  collection.find({}).toArray((error, documents) => {
    console.log("Found the following documents");
    console.log(documents);
  });

  // Update
  collection.updateOne({name: "Device 1"}, {$set: {status: "Online"}}, (error, result) => {
    console.log("Updated the document");
  });

  // Delete
  collection.deleteOne({name: "Device 1"}, (error, result) => {
    console.log("Deleted the document");
  });

  client.close();
});