簡體   English   中英

本機MongoDB驅動程序Node.js-我們應該存儲集合嗎?

[英]Native MongoDB Driver Node.js - should we store collections?

我沒有找到任何概述可以保留對集合的引用的好主意的文檔,以便在建立數據庫連接后可以重新使用它。

例如,在我們的服務器啟動期間調用的database.ts中。 它將獲取這些集合並將其存儲在模塊中使用,然后可以在整個項目中作為參考。

存儲集合的示例

 /*database.ts*/ //module to keep 1 connection alive and allow us to have 1 instance of our collections. import {MongoClient, Db, Collection } from 'mongodb'; let uri: string = 'connection_string'; export let db: Db; export let usrCollection: Collection; export let bookCollection: Collection; export function initDb(cb: any) { MongoClient.connect(uri, function(err, database) { //handle err db = database; cb(); //returns now since db is assigned. }); } export function initCollections() { usrCollection = db.collection('users'); //non-async bookCollection = db.collection('book'); //non-async } /*app.ts*/ //in our express app when it start up import {db, initCollections, initDb} from './database'; initDb(function() { //this will hold up our server from starting BUT //there is no reason to make it async. initCollections(); }); 

這種模式/構建的短處是什么? 我應該改進哪些方面,以及應該特別注意管理集合而避免性能下降。這種模式將使我的源代碼錯誤免費或容易找到並在將來擴展嗎? 還是有更好的模式-除了用於mongoose之類的node.js解決方案的本地mongodb驅動程序之外,請不要使用ext庫。

海事組織,這不是一個好習慣。 database.ts用戶必須在使用它們之前確保已初始化這些集合。 我什至不會導出任何內部集合,因為用戶永遠不必關心數據庫的結構。 您應該導出一些操作函數,例如function addUser(user: User) {/.../} MS創建了一個簡潔的代碼示例

//編輯。 是的,您可以在內部存儲集合引用,這樣就不必每次都鍵入集合名稱。 通過忽略單數和復數很容易引入錯誤。 最佳做法是:

import mongodb = require('mongodb');

const server = new mongodb.Server('localhost', 27017, {auto_reconnect: true})
const db = new mongodb.Db('mydb', server, { w: 1 });
db.open(function() {});
const userCollection =db.collection("users");
const bookCollection = db.collection("book"); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM