Ví dụ api phần còn lại của tập bản đồ mongodb

Trước Atlas, tôi đã sử dụng mLab. mLab sau đó đã được MongoDB mua lại vào năm ngoái. Khá giống với mLab, MongoDB Atlas là cách dễ nhất để có phiên bản MongoDB trên đám mây

Show

Tại sao?

  • 💲 0 đô la. Tôi không phải là nhà quảng cáo cho MongoDB, nhưng tôi thích dịch vụ này và dịch vụ này sẽ không phá sản ❌🔨🐖, vì. tốt, nó MIỄN PHÍ không ràng buộc với dung lượng lên tới 512 MB. Hoàn hảo cho các dự án phụ nhỏ

  • 🏃‍♂️ Nhanh chóng, đơn giản và nhanh chóng. không có tập tin cài đặt và cấu hình. Sau khi đăng ký và tạo cụm (mất 5 phút), bạn đã hoàn tất

  • ☁ Đó là trên đám mây. Không chạy trong máy của bạn dưới dạng dịch vụ Mongo. Không có trong tệp đĩa như

    // server.js
    
    const express = require("express");
    const server = express();
    
    const body_parser = require("body-parser");
    
    // parse JSON (application/json content-type)
    server.use(body_parser.json());
    
    const port = 4000;
    
    // << db setup >>
    const db = require("./db");
    const dbName = "data";
    const collectionName = "movies";
    
    // << db init >>
    
    server.listen(port, () => {
        console.log(`Server listening at ${port}`);
    });
    
    0. Bạn có thể quản lý nó từ mọi nơi thông qua ứng dụng web Atlas. Đối với ứng dụng của bạn, bạn chỉ cần một URL kết nối để truy cập db

  • 😎 Giao diện người dùng rất tuyệt. Bảng điều khiển Atlas rất trực quan và người dùng lần đầu sẽ thấy dễ sử dụng với các bước và gợi ý trực quan

Thiết lập đám mây

Có thể có một số khác biệt nhỏ về ảnh chụp màn hình đối với giao diện người dùng Atlas thực tế vào thời điểm bạn thực hiện việc này, nhưng các bước được mô tả sẽ đưa bạn đến kết quả tương tự

1. Đầu tiên đăng ký tại đây

https. //www. mongodb. com/đám mây/bản đồ/đăng ký

Ví dụ api phần còn lại của tập bản đồ mongodb

2. Tạo một Starter Cluster bậc miễn phí

Ví dụ api phần còn lại của tập bản đồ mongodb

Starter Cluster M0 miễn phí đi kèm với Bộ nhớ 512 MB, RAM và vCPU dùng chung

Điều này là quá đủ cho dự án Node khởi đầu của chúng tôi

  • Vùng cụm. bạn có thể chọn bất kỳ nhà cung cấp nào (AWS, Google, Azure) và khu vực gần bạn nhất có Bậc miễn phí. Đối với tôi, đó là AWS us-east-1

Ví dụ api phần còn lại của tập bản đồ mongodb

  • Bạn có thể để phần còn lại ở mặc định MIỄN PHÍ

  • Tạo cụm

Quá trình tạo và cung cấp có thể mất vài phút

  • Sau đó, bảng điều khiển xuất hiện với bảng điều khiển bên chứa tất cả các tùy chọn cần thiết để quản lý cụm

Ví dụ api phần còn lại của tập bản đồ mongodb

3. Kết nối với cụm

Nhấp vào [Kết nối] trong Cụm chúng tôi vừa tạo

Hộp thoại xuất hiện cung cấp các tùy chọn để

  1. Danh sách trắng địa chỉ IP của bạn
  2. Tạo người dùng MongoDB

Ví dụ api phần còn lại của tập bản đồ mongodb

3. 1 địa chỉ IP danh sách trắng

Danh sách trắng có nghĩa là chỉ cho phép truy cập vào các thực thể được chọn (do đó đáng tin cậy)

  • [Thêm địa chỉ IP hiện tại của bạn], địa chỉ này sẽ tự động lấy địa chỉ IP công cộng hiện tại của bạn. Tùy chọn thêm một mô tả, chẳng hạn như "Địa chỉ IP nhà riêng của tôi"

    • ❗ Nhớ làm lại bước này khi đổi WiFi, e. g. khi di chuyển từ quán cà phê về WiFi gia đình
    • 💡 Nếu bạn đang sử dụng mạng wi-fi công cộng, bạn có thể sử dụng một dịch vụ như https. // whatismyipaddress. com/ để lấy địa chỉ công cộng IPv4 của bạn, vì
      // server.js
      
      const express = require("express");
      const server = express();
      
      const body_parser = require("body-parser");
      
      // parse JSON (application/json content-type)
      server.use(body_parser.json());
      
      const port = 4000;
      
      // << db setup >>
      const db = require("./db");
      const dbName = "data";
      const collectionName = "movies";
      
      // << db init >>
      
      server.listen(port, () => {
          console.log(`Server listening at ${port}`);
      });
      
      1 hoặc
      // server.js
      
      const express = require("express");
      const server = express();
      
      const body_parser = require("body-parser");
      
      // parse JSON (application/json content-type)
      server.use(body_parser.json());
      
      const port = 4000;
      
      // << db setup >>
      const db = require("./db");
      const dbName = "data";
      const collectionName = "movies";
      
      // << db init >>
      
      server.listen(port, () => {
          console.log(`Server listening at ${port}`);
      });
      
      2 có thể chỉ cung cấp cho bạn địa chỉ mạng nội bộ
    • 💣Bạn có thể sử dụng
      // server.js
      
      const express = require("express");
      const server = express();
      
      const body_parser = require("body-parser");
      
      // parse JSON (application/json content-type)
      server.use(body_parser.json());
      
      const port = 4000;
      
      // << db setup >>
      const db = require("./db");
      const dbName = "data";
      const collectionName = "movies";
      
      // << db init >>
      
      server.listen(port, () => {
          console.log(`Server listening at ${port}`);
      });
      
      3 để kích hoạt tất cả các địa chỉ IP ở mọi nơi, điều này giúp đơn giản hóa quy trình này nhưng lại RẤT KHÔNG AN TOÀN

3. 2 Tạo người dùng quản trị

Nhập tên người dùng và mật khẩu ưa thích của bạn. Đây sẽ là người dùng quản trị ("root") đầu tiên, sau đó là [Tạo người dùng MongoDB]

  • Giữ những thông tin xác thực này ở nơi tiện dụng vì chúng ta sẽ sử dụng chúng sau này

  • Đóng cửa sổ. Chúng tôi sẽ kết nối với cụm sau

4. 📃 Thêm dữ liệu mẫu

Từ chế độ xem cụm, hãy nhấp vào [Bộ sưu tập], sau đó nhấp vào [Thêm dữ liệu của riêng tôi]

Ví dụ api phần còn lại của tập bản đồ mongodb

  • Tương tự như bài trước, chúng ta sử dụng
    • tên cơ sở dữ liệu.
      // server.js
      
      const express = require("express");
      const server = express();
      
      const body_parser = require("body-parser");
      
      // parse JSON (application/json content-type)
      server.use(body_parser.json());
      
      const port = 4000;
      
      // << db setup >>
      const db = require("./db");
      const dbName = "data";
      const collectionName = "movies";
      
      // << db init >>
      
      server.listen(port, () => {
          console.log(`Server listening at ${port}`);
      });
      
      4
    • tên bộ sưu tập.
      // server.js
      
      const express = require("express");
      const server = express();
      
      const body_parser = require("body-parser");
      
      // parse JSON (application/json content-type)
      server.use(body_parser.json());
      
      const port = 4000;
      
      // << db setup >>
      const db = require("./db");
      const dbName = "data";
      const collectionName = "movies";
      
      // << db init >>
      
      server.listen(port, () => {
          console.log(`Server listening at ${port}`);
      });
      
      5

🎥 Các phim trong sê-ri này là từ IMDB. Bạn có thể sử dụng

// server.js

const express = require("express");
const server = express();

const body_parser = require("body-parser");

// parse JSON (application/json content-type)
server.use(body_parser.json());

const port = 4000;

// << db setup >>
const db = require("./db");
const dbName = "data";
const collectionName = "movies";

// << db init >>

server.listen(port, () => {
    console.log(`Server listening at ${port}`);
});
6 từ bất kỳ URL trang phim nào. e. g. Trong "The Lion King" trang
// server.js

const express = require("express");
const server = express();

const body_parser = require("body-parser");

// parse JSON (application/json content-type)
server.use(body_parser.json());

const port = 4000;

// << db setup >>
const db = require("./db");
const dbName = "data";
const collectionName = "movies";

// << db init >>

server.listen(port, () => {
    console.log(`Server listening at ${port}`);
});
7;

Chèn tài liệu

Ví dụ api phần còn lại của tập bản đồ mongodb

  • Chèn một mục nhập phim, như trước đây - Để lại
    // db.js
    ...
    // << db init >>
    db.initialize(dbName, collectionName, function(dbCollection) { // successCallback
        // get all items
        dbCollection.find().toArray(function(err, result) {
            if (err) throw err;
              console.log(result);
        });
    
        // << db CRUD routes >>
    
    }, function(err) { // failureCallback
        throw (err);
    });
    ...
    
    0 đã cho do Atlas cung cấp vì đây là nội bộ

Ví dụ api phần còn lại của tập bản đồ mongodb

  • Bây giờ chúng tôi thấy dữ liệu đã chèn trong bảng điều khiển. Thêm nhiều hơn như bạn muốn

Ví dụ api phần còn lại của tập bản đồ mongodb

Hoàn hảo. Bây giờ chúng tôi đã có dữ liệu. Thời gian kết nối với cụm

5. 🔌 Kết nối với cụm

Quay lại dạng xem Cụm, sau đó nhấp vào Kết nối trong cụm của chúng tôi

Ví dụ api phần còn lại của tập bản đồ mongodb

Chọn [Kết nối ứng dụng của bạn]

Ví dụ api phần còn lại của tập bản đồ mongodb

Để mặc định Node. js phiên bản 3+

Ví dụ api phần còn lại của tập bản đồ mongodb

Sao chép chuỗi kết nối. Chúng tôi sẽ sử dụng điều này trong bước tiếp theo

Bây giờ chúng ta đã sẵn sàng đi sâu vào code

Ví dụ api phần còn lại của tập bản đồ mongodb

Kết nối với db

1. Lấy mã bắt đầu từ bài học trước tại đây

https. //github. com/lenmorld/devto_posts/tree/master/quick_node_express_diskdb

  1. Cài đặt trình điều khiển
    // db.js
    ...
    // << db init >>
    db.initialize(dbName, collectionName, function(dbCollection) { // successCallback
        // get all items
        dbCollection.find().toArray(function(err, result) {
            if (err) throw err;
              console.log(result);
        });
    
        // << db CRUD routes >>
    
    }, function(err) { // failureCallback
        throw (err);
    });
    ...
    
    1

$ npm install mongodb

2. Tạo một tệp mới có tên // db.js ... // << db init >> db.initialize(dbName, collectionName, function(dbCollection) { // successCallback // get all items dbCollection.find().toArray(function(err, result) { if (err) throw err; console.log(result); }); // << db CRUD routes >> }, function(err) { // failureCallback throw (err); }); ... 2 trong thư mục gốc của ứng dụng

Sử dụng đoạn mã này và thay thế

// db.js
...
// << db init >>
db.initialize(dbName, collectionName, function(dbCollection) { // successCallback
    // get all items
    dbCollection.find().toArray(function(err, result) {
        if (err) throw err;
          console.log(result);
    });

    // << db CRUD routes >>

}, function(err) { // failureCallback
    throw (err);
});
...
3 bằng chuỗi kết nối của bạn

Nó sẽ trông hơi giống thế này

// db.js
...
// << db init >>
db.initialize(dbName, collectionName, function(dbCollection) { // successCallback
    // get all items
    dbCollection.find().toArray(function(err, result) {
        if (err) throw err;
          console.log(result);
    });

    // << db CRUD routes >>

}, function(err) { // failureCallback
    throw (err);
});
...
4

// db.js

// mongodb driver
const MongoClient = require("mongodb").MongoClient;

const dbConnectionUrl = "CONNECTION_STRING_FROM_ATLAS";

function initialize(
    dbName,
    dbCollectionName,
    successCallback,
    failureCallback
) {
    MongoClient.connect(dbConnectionUrl, function(err, dbInstance) {
        if (err) {
            console.log(`[MongoDB connection] ERROR: ${err}`);
            failureCallback(err); // this should be "caught" by the calling function
        } else {
            const dbObject = dbInstance.db(dbName);
            const dbCollection = dbObject.collection(dbCollectionName);
            console.log("[MongoDB connection] SUCCESS");

            successCallback(dbCollection);
        }
    });
}

module.exports = {
    initialize
};

  1. Hàm chấp nhận các chi tiết db trên đám mây của chúng tôi (tên db và tên bộ sưu tập) và các cuộc gọi lại
  2. Sau đó, nó kết nối với db đám mây của chúng tôi bằng phương thức trình điều khiển
    // db.js
    ...
    // << db init >>
    db.initialize(dbName, collectionName, function(dbCollection) { // successCallback
        // get all items
        dbCollection.find().toArray(function(err, result) {
            if (err) throw err;
              console.log(result);
        });
    
        // << db CRUD routes >>
    
    }, function(err) { // failureCallback
        throw (err);
    });
    ...
    
    5
  3. Sau khi thành công, nó gọi đối tượng
    // db.js
    ...
    // << db init >>
    db.initialize(dbName, collectionName, function(dbCollection) { // successCallback
        // get all items
        dbCollection.find().toArray(function(err, result) {
            if (err) throw err;
              console.log(result);
        });
    
        // << db CRUD routes >>
    
    }, function(err) { // failureCallback
        throw (err);
    });
    ...
    
    6 truyền đối tượng
    // db.js
    ...
    // << db init >>
    db.initialize(dbName, collectionName, function(dbCollection) { // successCallback
        // get all items
        dbCollection.find().toArray(function(err, result) {
            if (err) throw err;
              console.log(result);
        });
    
        // << db CRUD routes >>
    
    }, function(err) { // failureCallback
        throw (err);
    });
    ...
    
    7
    • Bất kỳ thất bại nào sẽ bị ném bởi
      // db.js
      ...
      // << db init >>
      db.initialize(dbName, collectionName, function(dbCollection) { // successCallback
          // get all items
          dbCollection.find().toArray(function(err, result) {
              if (err) throw err;
                console.log(result);
          });
      
          // << db CRUD routes >>
      
      }, function(err) { // failureCallback
          throw (err);
      });
      ...
      
      8
  4. Chúng tôi sẽ sử dụng
    // db.js
    ...
    // << db init >>
    db.initialize(dbName, collectionName, function(dbCollection) { // successCallback
        // get all items
        dbCollection.find().toArray(function(err, result) {
            if (err) throw err;
              console.log(result);
        });
    
        // << db CRUD routes >>
    
    }, function(err) { // failureCallback
        throw (err);
    });
    ...
    
    7 để thực thi các lệnh mongodb

Quay lại máy chủ của chúng tôi, chúng tôi sẽ bắt đầu $ npm install $ npm start 0 từ đầu

Chúng tôi sẽ sử dụng kết nối db đám mây thay vì

// server.js

const express = require("express");
const server = express();

const body_parser = require("body-parser");

// parse JSON (application/json content-type)
server.use(body_parser.json());

const port = 4000;

// << db setup >>
const db = require("./db");
const dbName = "data";
const collectionName = "movies";

// << db init >>

server.listen(port, () => {
    console.log(`Server listening at ${port}`);
});
0

// server.js

const express = require("express");
const server = express();

const body_parser = require("body-parser");

// parse JSON (application/json content-type)
server.use(body_parser.json());

const port = 4000;

// << db setup >>
const db = require("./db");
const dbName = "data";
const collectionName = "movies";

// << db init >>

server.listen(port, () => {
    console.log(`Server listening at ${port}`);
});

Trong

$ npm install
$ npm start
2, chúng tôi nhập
// db.js
...
// << db init >>
db.initialize(dbName, collectionName, function(dbCollection) { // successCallback
    // get all items
    dbCollection.find().toArray(function(err, result) {
        if (err) throw err;
          console.log(result);
    });

    // << db CRUD routes >>

}, function(err) { // failureCallback
    throw (err);
});
...
2 (để sử dụng phương pháp
$ npm install
$ npm start
4 của chúng tôi) và xác định các biến cho thông tin của db

4. Khởi tạo kết nối cơ sở dữ liệu

// db.js
...
// << db init >>
db.initialize(dbName, collectionName, function(dbCollection) { // successCallback
    // get all items
    dbCollection.find().toArray(function(err, result) {
        if (err) throw err;
          console.log(result);
    });

    // << db CRUD routes >>

}, function(err) { // failureCallback
    throw (err);
});
...

Chúng tôi

$ npm install
$ npm start
4 db với
$ npm install
$ npm start
6,
$ npm install
$ npm start
7 và một
// db.js
...
// << db init >>
db.initialize(dbName, collectionName, function(dbCollection) { // successCallback
    // get all items
    dbCollection.find().toArray(function(err, result) {
        if (err) throw err;
          console.log(result);
    });

    // << db CRUD routes >>

}, function(err) { // failureCallback
    throw (err);
});
...
6

Bên trong

// db.js
...
// << db init >>
db.initialize(dbName, collectionName, function(dbCollection) { // successCallback
    // get all items
    dbCollection.find().toArray(function(err, result) {
        if (err) throw err;
          console.log(result);
    });

    // << db CRUD routes >>

}, function(err) { // failureCallback
    throw (err);
});
...
6

  • Server listening at 4000
    [MongoDB connection] SUCCESS
    [ { _id: 5d7ed8f31c9d4400009c3775,
        id: 'tt0110357',
        name: 'The Lion King',
        genre: 'animation' } ]
    
    0 sử dụng
    Server listening at 4000
    [MongoDB connection] SUCCESS
    [ { _id: 5d7ed8f31c9d4400009c3775,
        id: 'tt0110357',
        name: 'The Lion King',
        genre: 'animation' } ]
    
    1, trả về một con trỏ

    • Con trỏ giống như một trình vòng lặp, trong đó bạn có thể thực hiện
      Server listening at 4000
      [MongoDB connection] SUCCESS
      [ { _id: 5d7ed8f31c9d4400009c3775,
          id: 'tt0110357',
          name: 'The Lion King',
          genre: 'animation' } ]
      
      2,
      Server listening at 4000
      [MongoDB connection] SUCCESS
      [ { _id: 5d7ed8f31c9d4400009c3775,
          id: 'tt0110357',
          name: 'The Lion King',
          genre: 'animation' } ]
      
      3, v.v.
  • Chuyển đổi con trỏ thành một mảng bằng phương pháp không đồng bộ

    Server listening at 4000
    [MongoDB connection] SUCCESS
    [ { _id: 5d7ed8f31c9d4400009c3775,
        id: 'tt0110357',
        name: 'The Lion King',
        genre: 'animation' } ]
    
    4

    • Trường hợp sử dụng của chúng ta trả về mảng đầy đủ sẽ đơn giản hơn là lặp lại con trỏ
  • Server listening at 4000
    [MongoDB connection] SUCCESS
    [ { _id: 5d7ed8f31c9d4400009c3775,
        id: 'tt0110357',
        name: 'The Lion King',
        genre: 'animation' } ]
    
    5 chạy sau khi chuyển đổi thành công con trỏ thành một mảng

    • Chúng tôi ghi lại kết quả ngay bây giờ, nhưng bạn có thể tưởng tượng mã để trả về phản hồi cho khách hàng tại đây

Bắt đầu máy chủ

$ npm install
$ npm start

cái nào nên cho

Server listening at 4000
[MongoDB connection] SUCCESS
[ { _id: 5d7ed8f31c9d4400009c3775,
    id: 'tt0110357',
    name: 'The Lion King',
    genre: 'animation' } ]

vâng. nó hoạt động

Ví dụ api phần còn lại của tập bản đồ mongodb

Bây giờ hãy hoàn thành tất cả các tuyến đường CRUD

tuyến đường CRUD

Dưới đây là danh sách các hoạt động CRUD-to-MongoDB cho trình xử lý tuyến đường của chúng tôi

Lưu ý rằng có khá nhiều sự khác biệt về cú pháp giữa hàm

// server.js

const express = require("express");
const server = express();

const body_parser = require("body-parser");

// parse JSON (application/json content-type)
server.use(body_parser.json());

const port = 4000;

// << db setup >>
const db = require("./db");
const dbName = "data";
const collectionName = "movies";

// << db init >>

server.listen(port, () => {
    console.log(`Server listening at ${port}`);
});
0 và hàm chính thức
// db.js
...
// << db init >>
db.initialize(dbName, collectionName, function(dbCollection) { // successCallback
    // get all items
    dbCollection.find().toArray(function(err, result) {
        if (err) throw err;
          console.log(result);
    });

    // << db CRUD routes >>

}, function(err) { // failureCallback
    throw (err);
});
...
5

CRUD OperationREST operationMongoClient OperationCreatePOST

Server listening at 4000
[MongoDB connection] SUCCESS
[ { _id: 5d7ed8f31c9d4400009c3775,
    id: 'tt0110357',
    name: 'The Lion King',
    genre: 'animation' } ]
8
Server listening at 4000
[MongoDB connection] SUCCESS
[ { _id: 5d7ed8f31c9d4400009c3775,
    id: 'tt0110357',
    name: 'The Lion King',
    genre: 'animation' } ]
9Read OneGET
// server.js
...
// << db CRUD routes >>
server.post("/items", (request, response) => {
    const item = request.body;
    dbCollection.insertOne(item, (error, result) => { // callback of insertOne
        if (error) throw error;
        // return updated list
        dbCollection.find().toArray((_error, _result) => { // callback of find
            if (_error) throw _error;
            response.json(_result);
        });
    });
});
0
// server.js
...
// << db CRUD routes >>
server.post("/items", (request, response) => {
    const item = request.body;
    dbCollection.insertOne(item, (error, result) => { // callback of insertOne
        if (error) throw error;
        // return updated list
        dbCollection.find().toArray((_error, _result) => { // callback of find
            if (_error) throw _error;
            response.json(_result);
        });
    });
});
1Read AllGET
Server listening at 4000
[MongoDB connection] SUCCESS
[ { _id: 5d7ed8f31c9d4400009c3775,
    id: 'tt0110357',
    name: 'The Lion King',
    genre: 'animation' } ]
8
// server.js
...
// << db CRUD routes >>
server.post("/items", (request, response) => {
    const item = request.body;
    dbCollection.insertOne(item, (error, result) => { // callback of insertOne
        if (error) throw error;
        // return updated list
        dbCollection.find().toArray((_error, _result) => { // callback of find
            if (_error) throw _error;
            response.json(_result);
        });
    });
});
3UpdatePUT
// server.js
...
// << db CRUD routes >>
server.post("/items", (request, response) => {
    const item = request.body;
    dbCollection.insertOne(item, (error, result) => { // callback of insertOne
        if (error) throw error;
        // return updated list
        dbCollection.find().toArray((_error, _result) => { // callback of find
            if (_error) throw _error;
            response.json(_result);
        });
    });
});
0
// server.js
...
// << db CRUD routes >>
server.post("/items", (request, response) => {
    const item = request.body;
    dbCollection.insertOne(item, (error, result) => { // callback of insertOne
        if (error) throw error;
        // return updated list
        dbCollection.find().toArray((_error, _result) => { // callback of find
            if (_error) throw _error;
            response.json(_result);
        });
    });
});
5DeleteDELETE
// server.js
...
// << db CRUD routes >>
server.post("/items", (request, response) => {
    const item = request.body;
    dbCollection.insertOne(item, (error, result) => { // callback of insertOne
        if (error) throw error;
        // return updated list
        dbCollection.find().toArray((_error, _result) => { // callback of find
            if (_error) throw _error;
            response.json(_result);
        });
    });
});
0
// server.js
...
// << db CRUD routes >>
server.post("/items", (request, response) => {
    const item = request.body;
    dbCollection.insertOne(item, (error, result) => { // callback of insertOne
        if (error) throw error;
        // return updated list
        dbCollection.find().toArray((_error, _result) => { // callback of find
            if (_error) throw _error;
            response.json(_result);
        });
    });
});
7

Tất cả các tuyến đường này đi vào điểm đánh dấu

// server.js
...
// << db CRUD routes >>
server.post("/items", (request, response) => {
    const item = request.body;
    dbCollection.insertOne(item, (error, result) => { // callback of insertOne
        if (error) throw error;
        // return updated list
        dbCollection.find().toArray((_error, _result) => { // callback of find
            if (_error) throw _error;
            response.json(_result);
        });
    });
});
8 trong mã của chúng tôi

i. Tạo ➕

// server.js
...
// << db CRUD routes >>
server.post("/items", (request, response) => {
    const item = request.body;
    dbCollection.insertOne(item, (error, result) => { // callback of insertOne
        if (error) throw error;
        // return updated list
        dbCollection.find().toArray((_error, _result) => { // callback of find
            if (_error) throw _error;
            response.json(_result);
        });
    });
});

  1. Đối với trình xử lý

    // server.js
    ...
    // << db CRUD routes >>
    server.post("/items", (request, response) => {
        const item = request.body;
        dbCollection.insertOne(item, (error, result) => { // callback of insertOne
            if (error) throw error;
            // return updated list
            dbCollection.find().toArray((_error, _result) => { // callback of find
                if (_error) throw _error;
                response.json(_result);
            });
        });
    });
    
    9, hãy sử dụng
    $ curl -X POST -H "Content-Type: application/json" --data '{"id": "tt0109830", "name": "Forrest
    Gump", "genre": "drama"}' http://localhost:4000/items
    
    [{"_id":"5de5c9d01c9d440000482ef0","id":"tt0110357","name":"The Lion King","genre":"animation"},{"_id":"5de7009967aec74a90f88d67","id":"tt0109830","name":"Forrest Gump","genre":"drama"}]
    
    0 để thêm phim từ
    $ curl -X POST -H "Content-Type: application/json" --data '{"id": "tt0109830", "name": "Forrest
    Gump", "genre": "drama"}' http://localhost:4000/items
    
    [{"_id":"5de5c9d01c9d440000482ef0","id":"tt0110357","name":"The Lion King","genre":"animation"},{"_id":"5de7009967aec74a90f88d67","id":"tt0109830","name":"Forrest Gump","genre":"drama"}]
    
    1 (được phân tích cú pháp bởi phần mềm trung gian
    $ curl -X POST -H "Content-Type: application/json" --data '{"id": "tt0109830", "name": "Forrest
    Gump", "genre": "drama"}' http://localhost:4000/items
    
    [{"_id":"5de5c9d01c9d440000482ef0","id":"tt0110357","name":"The Lion King","genre":"animation"},{"_id":"5de7009967aec74a90f88d67","id":"tt0109830","name":"Forrest Gump","genre":"drama"}]
    
    2)

  2. Trong

    Server listening at 4000
    [MongoDB connection] SUCCESS
    [ { _id: 5d7ed8f31c9d4400009c3775,
        id: 'tt0110357',
        name: 'The Lion King',
        genre: 'animation' } ]
    
    5 của
    $ curl -X POST -H "Content-Type: application/json" --data '{"id": "tt0109830", "name": "Forrest
    Gump", "genre": "drama"}' http://localhost:4000/items
    
    [{"_id":"5de5c9d01c9d440000482ef0","id":"tt0110357","name":"The Lion King","genre":"animation"},{"_id":"5de7009967aec74a90f88d67","id":"tt0109830","name":"Forrest Gump","genre":"drama"}]
    
    4, ném
    $ curl -X POST -H "Content-Type: application/json" --data '{"id": "tt0109830", "name": "Forrest
    Gump", "genre": "drama"}' http://localhost:4000/items
    
    [{"_id":"5de5c9d01c9d440000482ef0","id":"tt0110357","name":"The Lion King","genre":"animation"},{"_id":"5de7009967aec74a90f88d67","id":"tt0109830","name":"Forrest Gump","genre":"drama"}]
    
    5 nếu có.
    $ curl -X POST -H "Content-Type: application/json" --data '{"id": "tt0109830", "name": "Forrest
    Gump", "genre": "drama"}' http://localhost:4000/items
    
    [{"_id":"5de5c9d01c9d440000482ef0","id":"tt0110357","name":"The Lion King","genre":"animation"},{"_id":"5de7009967aec74a90f88d67","id":"tt0109830","name":"Forrest Gump","genre":"drama"}]
    
    6 không được sử dụng ở đây (_đó chỉ là phép tính toán thành công và
    // db.js
    ...
    // << db init >>
    db.initialize(dbName, collectionName, function(dbCollection) { // successCallback
        // get all items
        dbCollection.find().toArray(function(err, result) {
            if (err) throw err;
              console.log(result);
        });
    
        // << db CRUD routes >>
    
    }, function(err) { // failureCallback
        throw (err);
    });
    ...
    
    0 của tài liệu được chèn)

  3. Nhận danh sách đã cập nhật bằng cách sử dụng

    $ curl -X POST -H "Content-Type: application/json" --data '{"id": "tt0109830", "name": "Forrest
    Gump", "genre": "drama"}' http://localhost:4000/items
    
    [{"_id":"5de5c9d01c9d440000482ef0","id":"tt0110357","name":"The Lion King","genre":"animation"},{"_id":"5de7009967aec74a90f88d67","id":"tt0109830","name":"Forrest Gump","genre":"drama"}]
    
    8 và trả lại
    $ curl -X POST -H "Content-Type: application/json" --data '{"id": "tt0109830", "name": "Forrest
    Gump", "genre": "drama"}' http://localhost:4000/items
    
    [{"_id":"5de5c9d01c9d440000482ef0","id":"tt0110357","name":"The Lion King","genre":"animation"},{"_id":"5de7009967aec74a90f88d67","id":"tt0109830","name":"Forrest Gump","genre":"drama"}]
    
    9 làm phản hồi trong
    Server listening at 4000
    [MongoDB connection] SUCCESS
    [ { _id: 5d7ed8f31c9d4400009c3775,
        id: 'tt0110357',
        name: 'The Lion King',
        genre: 'animation' } ]
    
    5 của nó

Lưu ý hai cấp độ gọi lại tương tự ở đây. cuộc gọi lại bên ngoài của

$ curl -X POST -H "Content-Type: application/json" --data '{"id": "tt0109830", "name": "Forrest
Gump", "genre": "drama"}' http://localhost:4000/items

[{"_id":"5de5c9d01c9d440000482ef0","id":"tt0110357","name":"The Lion King","genre":"animation"},{"_id":"5de7009967aec74a90f88d67","id":"tt0109830","name":"Forrest Gump","genre":"drama"}]
4 và cuộc gọi lại bên trong của
server.get("/items/:id", (request, response) => {
    const itemId = request.params.id;

    dbCollection.findOne({ id: itemId }, (error, result) => {
        if (error) throw error;
        // return item
        response.json(result);
    });
});
2. Đây là lý do tại sao tôi sử dụng
server.get("/items/:id", (request, response) => {
    const itemId = request.params.id;

    dbCollection.findOne({ id: itemId }, (error, result) => {
        if (error) throw error;
        // return item
        response.json(result);
    });
});
3 ở bên trong để tránh xung đột tên. Nhưng hãy thoải mái đổi tên chúng 😉

Bài kiểm tra

$ curl -X POST -H "Content-Type: application/json" --data '{"id": "tt0109830", "name": "Forrest
Gump", "genre": "drama"}' http://localhost:4000/items

[{"_id":"5de5c9d01c9d440000482ef0","id":"tt0110357","name":"The Lion King","genre":"animation"},{"_id":"5de7009967aec74a90f88d67","id":"tt0109830","name":"Forrest Gump","genre":"drama"}]

ii. Đọc một cái 🕵️

server.get("/items/:id", (request, response) => {
    const itemId = request.params.id;

    dbCollection.findOne({ id: itemId }, (error, result) => {
        if (error) throw error;
        // return item
        response.json(result);
    });
});

  1. Lấy

    // server.js
    
    const express = require("express");
    const server = express();
    
    const body_parser = require("body-parser");
    
    // parse JSON (application/json content-type)
    server.use(body_parser.json());
    
    const port = 4000;
    
    // << db setup >>
    const db = require("./db");
    const dbName = "data";
    const collectionName = "movies";
    
    // << db init >>
    
    server.listen(port, () => {
        console.log(`Server listening at ${port}`);
    });
    
    6 trực tiếp từ các thông số (e. g.
    server.get("/items/:id", (request, response) => {
        const itemId = request.params.id;
    
        dbCollection.findOne({ id: itemId }, (error, result) => {
            if (error) throw error;
            // return item
            response.json(result);
        });
    });
    
    5 cho http. // localhost/mục/1234)

  2. Tìm mục có

    // server.js
    
    const express = require("express");
    const server = express();
    
    const body_parser = require("body-parser");
    
    // parse JSON (application/json content-type)
    server.use(body_parser.json());
    
    const port = 4000;
    
    // << db setup >>
    const db = require("./db");
    const dbName = "data";
    const collectionName = "movies";
    
    // << db init >>
    
    server.listen(port, () => {
        console.log(`Server listening at ${port}`);
    });
    
    6 bằng cách sử dụng
    server.get("/items/:id", (request, response) => {
        const itemId = request.params.id;
    
        dbCollection.findOne({ id: itemId }, (error, result) => {
            if (error) throw error;
            // return item
            response.json(result);
        });
    });
    
    7

server.get("/items/:id", (request, response) => {
    const itemId = request.params.id;

    dbCollection.findOne({ id: itemId }, (error, result) => {
        if (error) throw error;
        // return item
        response.json(result);
    });
});
8 chỉ là một đối tượng để bạn có thể sử dụng các cặp khóa-giá trị cho các truy vấn của mình. Chúng tôi sử dụng đối tượng truy vấn này cho
server.get("/items/:id", (request, response) => {
    const itemId = request.params.id;

    dbCollection.findOne({ id: itemId }, (error, result) => {
        if (error) throw error;
        // return item
        response.json(result);
    });
});
2,
// query can be:

{ id: 1 }; // find using id

{ name: "The Lion King" }; // find using name

{ id: 1, name: "The Lion King", genre: "action" }; // find using id, name and genre
0 và các lệnh MongoDB khác

// query can be:

{ id: 1 }; // find using id

{ name: "The Lion King" }; // find using name

{ id: 1, name: "The Lion King", genre: "action" }; // find using id, name and genre

  1. Trả lại hàng vào ngày
    // query can be:
    
    { id: 1 }; // find using id
    
    { name: "The Lion King" }; // find using name
    
    { id: 1, name: "The Lion King", genre: "action" }; // find using id, name and genre
    
    1

Bài kiểm tra

// db.js

// mongodb driver
const MongoClient = require("mongodb").MongoClient;

const dbConnectionUrl = "CONNECTION_STRING_FROM_ATLAS";

function initialize(
    dbName,
    dbCollectionName,
    successCallback,
    failureCallback
) {
    MongoClient.connect(dbConnectionUrl, function(err, dbInstance) {
        if (err) {
            console.log(`[MongoDB connection] ERROR: ${err}`);
            failureCallback(err); // this should be "caught" by the calling function
        } else {
            const dbObject = dbInstance.db(dbName);
            const dbCollection = dbObject.collection(dbCollectionName);
            console.log("[MongoDB connection] SUCCESS");

            successCallback(dbCollection);
        }
    });
}

module.exports = {
    initialize
};
0

iii. Đọc hết 🕵️

// db.js

// mongodb driver
const MongoClient = require("mongodb").MongoClient;

const dbConnectionUrl = "CONNECTION_STRING_FROM_ATLAS";

function initialize(
    dbName,
    dbCollectionName,
    successCallback,
    failureCallback
) {
    MongoClient.connect(dbConnectionUrl, function(err, dbInstance) {
        if (err) {
            console.log(`[MongoDB connection] ERROR: ${err}`);
            failureCallback(err); // this should be "caught" by the calling function
        } else {
            const dbObject = dbInstance.db(dbName);
            const dbCollection = dbObject.collection(dbCollectionName);
            console.log("[MongoDB connection] SUCCESS");

            successCallback(dbCollection);
        }
    });
}

module.exports = {
    initialize
};
1

Trả lại tất cả các mục trong bộ sưu tập trong phản hồi, tương tự trong POST /items

Bài kiểm tra

// db.js

// mongodb driver
const MongoClient = require("mongodb").MongoClient;

const dbConnectionUrl = "CONNECTION_STRING_FROM_ATLAS";

function initialize(
    dbName,
    dbCollectionName,
    successCallback,
    failureCallback
) {
    MongoClient.connect(dbConnectionUrl, function(err, dbInstance) {
        if (err) {
            console.log(`[MongoDB connection] ERROR: ${err}`);
            failureCallback(err); // this should be "caught" by the calling function
        } else {
            const dbObject = dbInstance.db(dbName);
            const dbCollection = dbObject.collection(dbCollectionName);
            console.log("[MongoDB connection] SUCCESS");

            successCallback(dbCollection);
        }
    });
}

module.exports = {
    initialize
};
2

iv. Cập nhật ✏️

// db.js

// mongodb driver
const MongoClient = require("mongodb").MongoClient;

const dbConnectionUrl = "CONNECTION_STRING_FROM_ATLAS";

function initialize(
    dbName,
    dbCollectionName,
    successCallback,
    failureCallback
) {
    MongoClient.connect(dbConnectionUrl, function(err, dbInstance) {
        if (err) {
            console.log(`[MongoDB connection] ERROR: ${err}`);
            failureCallback(err); // this should be "caught" by the calling function
        } else {
            const dbObject = dbInstance.db(dbName);
            const dbCollection = dbObject.collection(dbCollectionName);
            console.log("[MongoDB connection] SUCCESS");

            successCallback(dbCollection);
        }
    });
}

module.exports = {
    initialize
};
3

  1. Lấy

    // server.js
    
    const express = require("express");
    const server = express();
    
    const body_parser = require("body-parser");
    
    // parse JSON (application/json content-type)
    server.use(body_parser.json());
    
    const port = 4000;
    
    // << db setup >>
    const db = require("./db");
    const dbName = "data";
    const collectionName = "movies";
    
    // << db init >>
    
    server.listen(port, () => {
        console.log(`Server listening at ${port}`);
    });
    
    6 từ params và
    // query can be:
    
    { id: 1 }; // find using id
    
    { name: "The Lion King" }; // find using name
    
    { id: 1, name: "The Lion King", genre: "action" }; // find using id, name and genre
    
    3 từ body (đến
    // query can be:
    
    { id: 1 }; // find using id
    
    { name: "The Lion King" }; // find using name
    
    { id: 1, name: "The Lion King", genre: "action" }; // find using id, name and genre
    
    4)

  2. Cập nhật mục với

    // server.js
    
    const express = require("express");
    const server = express();
    
    const body_parser = require("body-parser");
    
    // parse JSON (application/json content-type)
    server.use(body_parser.json());
    
    const port = 4000;
    
    // << db setup >>
    const db = require("./db");
    const dbName = "data";
    const collectionName = "movies";
    
    // << db init >>
    
    server.listen(port, () => {
        console.log(`Server listening at ${port}`);
    });
    
    6 và đặt thành
    // query can be:
    
    { id: 1 }; // find using id
    
    { name: "The Lion King" }; // find using name
    
    { id: 1, name: "The Lion King", genre: "action" }; // find using id, name and genre
    
    3, sử dụng
    // query can be:
    
    { id: 1 }; // find using id
    
    { name: "The Lion King" }; // find using name
    
    { id: 1, name: "The Lion King", genre: "action" }; // find using id, name and genre
    
    7

  • Lưu ý việc sử dụng
    // query can be:
    
    { id: 1 }; // find using id
    
    { name: "The Lion King" }; // find using name
    
    { id: 1, name: "The Lion King", genre: "action" }; // find using id, name and genre
    
    8 dành riêng cho MongoDB
  1. Trả lại danh sách đã cập nhật, như trong
    // server.js
    ...
    // << db CRUD routes >>
    server.post("/items", (request, response) => {
        const item = request.body;
        dbCollection.insertOne(item, (error, result) => { // callback of insertOne
            if (error) throw error;
            // return updated list
            dbCollection.find().toArray((_error, _result) => { // callback of find
                if (_error) throw _error;
                response.json(_result);
            });
        });
    });
    
    9 và
    // db.js
    
    // mongodb driver
    const MongoClient = require("mongodb").MongoClient;
    
    const dbConnectionUrl = "CONNECTION_STRING_FROM_ATLAS";
    
    function initialize(
        dbName,
        dbCollectionName,
        successCallback,
        failureCallback
    ) {
        MongoClient.connect(dbConnectionUrl, function(err, dbInstance) {
            if (err) {
                console.log(`[MongoDB connection] ERROR: ${err}`);
                failureCallback(err); // this should be "caught" by the calling function
            } else {
                const dbObject = dbInstance.db(dbName);
                const dbCollection = dbObject.collection(dbCollectionName);
                console.log("[MongoDB connection] SUCCESS");
    
                successCallback(dbCollection);
            }
        });
    }
    
    module.exports = {
        initialize
    };
    
    00

Bài kiểm tra

Có thể bạn nghĩ "Vua sư tử" là một bộ phim truyền hình, vì. tốt, tôi sẽ không làm hỏng nó. 🤫 🦁

// db.js

// mongodb driver
const MongoClient = require("mongodb").MongoClient;

const dbConnectionUrl = "CONNECTION_STRING_FROM_ATLAS";

function initialize(
    dbName,
    dbCollectionName,
    successCallback,
    failureCallback
) {
    MongoClient.connect(dbConnectionUrl, function(err, dbInstance) {
        if (err) {
            console.log(`[MongoDB connection] ERROR: ${err}`);
            failureCallback(err); // this should be "caught" by the calling function
        } else {
            const dbObject = dbInstance.db(dbName);
            const dbCollection = dbObject.collection(dbCollectionName);
            console.log("[MongoDB connection] SUCCESS");

            successCallback(dbCollection);
        }
    });
}

module.exports = {
    initialize
};
4

v. Xóa ❌

// db.js

// mongodb driver
const MongoClient = require("mongodb").MongoClient;

const dbConnectionUrl = "CONNECTION_STRING_FROM_ATLAS";

function initialize(
    dbName,
    dbCollectionName,
    successCallback,
    failureCallback
) {
    MongoClient.connect(dbConnectionUrl, function(err, dbInstance) {
        if (err) {
            console.log(`[MongoDB connection] ERROR: ${err}`);
            failureCallback(err); // this should be "caught" by the calling function
        } else {
            const dbObject = dbInstance.db(dbName);
            const dbCollection = dbObject.collection(dbCollectionName);
            console.log("[MongoDB connection] SUCCESS");

            successCallback(dbCollection);
        }
    });
}

module.exports = {
    initialize
};
5

Ở đây, chỉ cần có

// server.js

const express = require("express");
const server = express();

const body_parser = require("body-parser");

// parse JSON (application/json content-type)
server.use(body_parser.json());

const port = 4000;

// << db setup >>
const db = require("./db");
const dbName = "data";
const collectionName = "movies";

// << db init >>

server.listen(port, () => {
    console.log(`Server listening at ${port}`);
});
6 từ tham số mà chúng tôi chuyển đến
// db.js

// mongodb driver
const MongoClient = require("mongodb").MongoClient;

const dbConnectionUrl = "CONNECTION_STRING_FROM_ATLAS";

function initialize(
    dbName,
    dbCollectionName,
    successCallback,
    failureCallback
) {
    MongoClient.connect(dbConnectionUrl, function(err, dbInstance) {
        if (err) {
            console.log(`[MongoDB connection] ERROR: ${err}`);
            failureCallback(err); // this should be "caught" by the calling function
        } else {
            const dbObject = dbInstance.db(dbName);
            const dbCollection = dbObject.collection(dbCollectionName);
            console.log("[MongoDB connection] SUCCESS");

            successCallback(dbCollection);
        }
    });
}

module.exports = {
    initialize
};
02

Như trước đây, bạn có thể dễ dàng tạo một truy vấn theo nhu cầu của mình, vì nó chỉ là một đối tượng

🤸‍♀️ Thử thách. mô đun hóa

// db.js

// mongodb driver
const MongoClient = require("mongodb").MongoClient;

const dbConnectionUrl = "CONNECTION_STRING_FROM_ATLAS";

function initialize(
    dbName,
    dbCollectionName,
    successCallback,
    failureCallback
) {
    MongoClient.connect(dbConnectionUrl, function(err, dbInstance) {
        if (err) {
            console.log(`[MongoDB connection] ERROR: ${err}`);
            failureCallback(err); // this should be "caught" by the calling function
        } else {
            const dbObject = dbInstance.db(dbName);
            const dbCollection = dbObject.collection(dbCollectionName);
            console.log("[MongoDB connection] SUCCESS");

            successCallback(dbCollection);
        }
    });
}

module.exports = {
    initialize
};
03 vì chúng tôi đang sử dụng nó ở 3 nơi

Bài kiểm tra

// db.js

// mongodb driver
const MongoClient = require("mongodb").MongoClient;

const dbConnectionUrl = "CONNECTION_STRING_FROM_ATLAS";

function initialize(
    dbName,
    dbCollectionName,
    successCallback,
    failureCallback
) {
    MongoClient.connect(dbConnectionUrl, function(err, dbInstance) {
        if (err) {
            console.log(`[MongoDB connection] ERROR: ${err}`);
            failureCallback(err); // this should be "caught" by the calling function
        } else {
            const dbObject = dbInstance.db(dbName);
            const dbCollection = dbObject.collection(dbCollectionName);
            console.log("[MongoDB connection] SUCCESS");

            successCallback(dbCollection);
        }
    });
}

module.exports = {
    initialize
};
6

ghi chú

  1. Gọi lại ??. , tại sao điều này thay vì ES6 Promises, hoặc ES7 async/await
  • // db.js
    
    // mongodb driver
    const MongoClient = require("mongodb").MongoClient;
    
    const dbConnectionUrl = "CONNECTION_STRING_FROM_ATLAS";
    
    function initialize(
        dbName,
        dbCollectionName,
        successCallback,
        failureCallback
    ) {
        MongoClient.connect(dbConnectionUrl, function(err, dbInstance) {
            if (err) {
                console.log(`[MongoDB connection] ERROR: ${err}`);
                failureCallback(err); // this should be "caught" by the calling function
            } else {
                const dbObject = dbInstance.db(dbName);
                const dbCollection = dbObject.collection(dbCollectionName);
                console.log("[MongoDB connection] SUCCESS");
    
                successCallback(dbCollection);
            }
        });
    }
    
    module.exports = {
        initialize
    };
    
    04 chỉ hỗ trợ các cuộc gọi lại, nhưng chúng tôi sẽ quảng cáo (và không đồng bộ-chờ đợi-ify) những cuộc gọi lại này trong bài học tiếp theo, vì thành thật mà nói, chúng bắt đầu trông giống như địa ngục cuộc gọi lại. Xem bài đăng này để biết danh sách thú vị về địa ngục gọi lại

Ví dụ api phần còn lại của tập bản đồ mongodb

Cách thoát khỏi địa ngục cuộc gọi lại với lời hứa JavaScript

AmberJ ・ 21 Oct '19 ・ 4 phút đọc

#javascript #người mới bắt đầu

  1. Tại sao chúng tôi trả lại tất cả các mục trong phản hồi tạo, cập nhật, xóa?
  • Có rất nhiều tùy chọn về những việc cần làm để đồng bộ hóa giao diện người dùng và phụ trợ sau khi thay đổi và bản thân nó cũng là một chủ đề Kiến trúc phần mềm

Bài viết không còn nữa

  • Ở đây, chúng tôi chỉ trả lại các mục đã cập nhật cho giao diện người dùng sau khi tạo, cập nhật và xóa. Chúng tôi để giao diện người dùng (e. g. React, Vue, Angular, Vanilla JS) cập nhật trạng thái và chế độ xem từ thông tin đó

Đây là Mã hoàn chỉnh

https. //github. com/lenmorld/devto_posts/tree/master/quick_node_express_mongodb

Ví dụ api phần còn lại của tập bản đồ mongodb

"Được rồi, thật tuyệt. Nhưng tôi có thể làm gì với điều này?

✅ Phục vụ các tệp HTML
✅ API REST
✅ Cơ sở dữ liệu đám mây bền bỉ

Bây giờ, đây là một máy chủ thực tế cho một dự án nhỏ. Thêm nhiều tuyến đường hơn, lưu một số dữ liệu trong db thông qua các yêu cầu API. Chỉ cần thêm giao diện người dùng. ™

Tiếp theo

(Trong tiến trình)

  • MongoDB gọi lại Promises và Async/Await

Bài viết này là một phần của loạt bài Node+Express mà tôi đang thực hiện

Trong thời gian chờ đợi, nếu bạn không thể có đủ Node+Express 🤓,
kiểm tra hội thảo Node của tôi (Github repo và slide)

lenmorld/node_workshop

Xây dựng máy chủ và API cho ứng dụng web tiếp theo của bạn, sử dụng Node, Express và MongoDB

hội thảo nút

theo dõi hội thảo

// db.js

// mongodb driver
const MongoClient = require("mongodb").MongoClient;

const dbConnectionUrl = "CONNECTION_STRING_FROM_ATLAS";

function initialize(
    dbName,
    dbCollectionName,
    successCallback,
    failureCallback
) {
    MongoClient.connect(dbConnectionUrl, function(err, dbInstance) {
        if (err) {
            console.log(`[MongoDB connection] ERROR: ${err}`);
            failureCallback(err); // this should be "caught" by the calling function
        } else {
            const dbObject = dbInstance.db(dbName);
            const dbCollection = dbObject.collection(dbCollectionName);
            console.log("[MongoDB connection] SUCCESS");

            successCallback(dbCollection);
        }
    });
}

module.exports = {
    initialize
};
7

để phát triển mới nhất

// db.js

// mongodb driver
const MongoClient = require("mongodb").MongoClient;

const dbConnectionUrl = "CONNECTION_STRING_FROM_ATLAS";

function initialize(
    dbName,
    dbCollectionName,
    successCallback,
    failureCallback
) {
    MongoClient.connect(dbConnectionUrl, function(err, dbInstance) {
        if (err) {
            console.log(`[MongoDB connection] ERROR: ${err}`);
            failureCallback(err); // this should be "caught" by the calling function
        } else {
            const dbObject = dbInstance.db(dbName);
            const dbCollection = dbObject.collection(dbCollectionName);
            console.log("[MongoDB connection] SUCCESS");

            successCallback(dbCollection);
        }
    });
}

module.exports = {
    initialize
};
8

Tạo một. tập tin env trên root

// db.js

// mongodb driver
const MongoClient = require("mongodb").MongoClient;

const dbConnectionUrl = "CONNECTION_STRING_FROM_ATLAS";

function initialize(
    dbName,
    dbCollectionName,
    successCallback,
    failureCallback
) {
    MongoClient.connect(dbConnectionUrl, function(err, dbInstance) {
        if (err) {
            console.log(`[MongoDB connection] ERROR: ${err}`);
            failureCallback(err); // this should be "caught" by the calling function
        } else {
            const dbObject = dbInstance.db(dbName);
            const dbCollection = dbObject.collection(dbCollectionName);
            console.log("[MongoDB connection] SUCCESS");

            successCallback(dbCollection);
        }
    });
}

module.exports = {
    initialize
};
9


Xem trên GitHub





Ở đây chúng tôi đã thảo luận
  • Sử dụng Nút và Express
  • Định tuyến, yêu cầu và phản hồi
  • Xây dựng API REST
  • Các mẫu do máy chủ kết xuất
  • Kết nối với cơ sở dữ liệu NoSQL (mongo)
  • Sử dụng các API bên ngoài, chẳng hạn như Spotify
  • và nhiều hơn nữa

Chúc mừng máy chủ. 🤓


Bây giờ, tất cả cuộc nói chuyện Mongo này làm tôi đói
Tôi sẽ ăn một ít "Hopia Mongo" (bánh ngọt Philippines nhân đậu) yêu thích của mình🌱

Ví dụ api phần còn lại của tập bản đồ mongodb

Ảnh từ FoxyFolksy trong bài viết "Hopia Recipe- Munggo And Ube Filling" src. https. //www. cáo già. com/hopia-recipe-munggo-ube-filling/

Làm cách nào để kết nối API REST với MongoDB?

Bước 1. Thiết lập dự án
Bước 2. Cài đặt phụ thuộc ứng dụng
Bước 3. Mã vận hành
Bước 4. Ứng dụng thử nghiệm cho MongoDB REST API
Bước 5. Thiết lập kết nối với MongoDB REST API
Bước 6. Xây dựng điểm cuối API MongoDB REST
Bước 7. Kiểm tra API MongoDB REST

MongoDB có hỗ trợ API REST không?

API dữ liệu Atlas là một API giống như REST được quản lý hoàn toàn , cho phép bạn truy cập dữ liệu MongoDB Atlas của mình và thực hiện các thao tác và tổng hợp CRUD một cách dễ dàng. Sau khi được bật trên một cụm, bạn có thể đạt được tất cả các hoạt động CRUD ngay lập tức thông qua một URL, chỉ với một khóa API.

MongoDB Atlas có phải là API không?

API dữ liệu Atlas MongoDB cho phép bạn đọc và ghi dữ liệu trong Atlas với các yêu cầu HTTPS tiêu chuẩn . Để sử dụng API dữ liệu, tất cả những gì bạn cần là ứng dụng khách HTTPS và khóa API hợp lệ. Máy khách gửi yêu cầu đến các điểm cuối cụ thể, mỗi điểm đại diện cho một hoạt động MongoDB.

Làm cách nào để tìm nạp dữ liệu từ API trong MongoDB?

Bạn có thể sử dụng thao tác đọc để truy xuất dữ liệu từ cơ sở dữ liệu MongoDB của mình . Có nhiều loại thao tác đọc truy cập dữ liệu theo những cách khác nhau. Nếu bạn muốn yêu cầu kết quả dựa trên một bộ tiêu chí từ bộ dữ liệu hiện có, bạn có thể sử dụng thao tác tìm chẳng hạn như phương thức find() hoặc findOne().