天天看點

如何将MongoDB與Node.js結合使用

If you are unfamiliar with MongoDB check our guide on its basics and on how to install and use it :)

如果您不熟悉MongoDB,請檢視我們的指南以了解其基礎知識以及如何安裝和使用它:)

We’ll be using the official

mongodb

npm package. If you already have a Node.js project you are working on, install it using

我們将使用官方的

mongodb

npm軟體包。 如果您已經在使用Node.js項目,請使用

npm install mongodb
           

If you start from scratch, create a new folder with your terminal and run

npm init -y

to start up a new Node.js project, and then run the

npm install mongodb

command.

如果從頭開始,請在終端上建立一個新檔案夾,然後運作

npm init -y

啟動一個新的Node.js項目,然後運作

npm install mongodb

指令。

連接配接到MongoDB (Connecting to MongoDB)

You require the

mongodb

package and you get the MongoClient object from it.

您需要

mongodb

軟體包,并從中擷取MongoClient對象。

const mongo = require('mongodb').MongoClient
           

Create a URL to the MongoDB server. If you use MongoDB locally, the URL will be something like

mongodb://localhost:27017

, as

27017

is the default port.

建立一個指向MongoDB伺服器的URL。 如果您在本地使用MongoDB,則URL将類似于

mongodb://localhost:27017

,因為

27017

是預設端口。

const url = 'mongodb://localhost:27017'
           

Then use the

mongo.connect()

method to get the reference to the MongoDB instance client:

然後使用

mongo.connect()

方法擷取對MongoDB執行個體用戶端的引用:

mongo.connect(url, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  }, (err, client) => {
  if (err) {
    console.error(err)
    return
  }
  //...
})
           

Now you can select a database using the

client.db()

method:

現在,您可以使用

client.db()

方法選擇一個資料庫:

const db = client.db('kennel')
           

建立并擷取集合 (Create and get a collection)

You can get a collection by using the

db.collection()

method. If the collection does not exist yet, it’s created.

您可以使用

db.collection()

方法獲得一個集合。 如果該集合尚不存在,則建立它。

const collection = db.collection('dogs')
           

将資料插入到文檔集合中 (Insert data into a collection a Document)

Add to app.js the following function which uses the

insertOne()

method to add an object

dogs

collection.

将以下函數添加到app.js中,該函數使用

insertOne()

方法添加對象

dogs

集合。

collection.insertOne({name: 'Roger'}, (err, result) => {

})
           

You can add multiple items using

insertMany()

, passing an array as the first parameter:

您可以使用

insertMany()

添加多個項目,并将數組作為第一個參數傳遞:

collection.insertMany([{name: 'Togo'}, {name: 'Syd'}], (err, result) => {

})
           

查找所有檔案 (Find all documents)

Use the

find()

method on the collection to get all the documents added to the collection:

在集合上使用

find()

方法來擷取添加到集合中的所有文檔:

collection.find().toArray((err, items) => {
  console.log(items)
})
           

查找特定檔案 (Find a specific document)

Pass an object to the

find()

method to filter the collection based on what you need to retrieve:

将對象傳遞給

find()

方法以根據需要檢索的内容過濾集合:

collection.find({name: 'Togo'}).toArray((err, items) => {
  console.log(items)
})
           

If you know you are going to get one element, you can skip the

toArray()

conversion of the cursor by calling

findOne()

:

如果知道要擷取一個元素,則可以通過調用

findOne()

來跳過遊标的

toArray()

轉換:

collection.findOne({name: 'Togo'}, (err, item) => {
  console.log(item)
})
           

更新現有文檔 (Update an existing document)

Use the

updateOne()

method to update a document:

使用

updateOne()

方法更新文檔:

collection.updateOne({name: 'Togo'}, {'$set': {'name': 'Togo2'}}, (err, item) => {
  console.log(item)
})
           

删除檔案 (Delete a document)

Use the

deleteOne()

method to delete a document:

使用

deleteOne()

方法删除文檔:

collection.deleteOne({name: 'Togo'}, (err, item) => {
  console.log(item)
})
           

斷開連接配接 (Closing the connection)

Once you are done with the operations you can call the

close()

method on the client object:

完成操作後,您可以在用戶端對象上調用

close()

方法:

client.close()
           

使用Promise或異步/等待 (Use promises or async/await)

I posted all those examples using the callback syntax. This API supports promises (and async/await) as well.

我使用回調文法釋出了所有這些示例。 該API也支援promises (和async / await )。

For example this

例如這個

collection.findOne({name: 'Togo'}, (err, item) => {
  console.log(item)
})
           

Can be used with promises:

可以與promises一起使用:

collection.findOne({name: 'Togo'})
  .then(item => {
    console.log(item)
  })
  .catch(err => {
  console.error(err)
  })
           

or async/await:

或異步/等待:

const find = async () => {
  try {
    const item = await collection.findOne({name: 'Togo'})
  } catch(err => {
  console.error(err)
  })
}

find()
           
翻譯自: https://flaviocopes.com/node-mongodb/