Socket
Socket
Sign inDemoInstall

@condor-labs/mongodb

Package Overview
Dependencies
242
Maintainers
5
Versions
30
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    @condor-labs/mongodb

This module provide and usefull helper to use mongoose library.


Version published
Weekly downloads
438
decreased by-75.79%
Maintainers
5
Created
Weekly downloads
 

Readme

Source

This module provide and usefull helper to use mongoose library.

See official documentation here.

Compatibility

The minimum supported version of Node.js is v8.

How to use it

To use the library you just need to follow the following steps

Install the library with npm

npm  install @condor-labs/mongodb

Import the library:

const mongodb = require("@condor-labs/mongodb")(settings);

settings array of object properties

those are the properties for each connection object

PropertyDefaultDescription
connectionName (String)It is a unique value that will indentify the connection you are using
host (String)127.0.0.1The host name of the database you are connecting to. In case you want to connect to mongo Atlas via cluster.
A) You must check the connection metrics of your cluster.
B) Copy the hosts of your metrics and concatenate them in the host property of your connection configuration to mongo example: in its connection parameters. host: 'cluster0-shard-00-00.ksccs.mongodbnet'cluster0-shard-00-01.ksccs.mongodb.net,cluster0-shard-00-02.ksccs.mongodb.net'
keep in mind which host property receives one or multiple hosts.
port (Number)27017The port number to connect to.
user (String)The username for authentication. This option is mongoose-specific, they are equivalent to the MongoDB driver's auth.username options.
password (String)The password for authentication. This option is mongoose-specific, they are equivalent to the MongoDB driver's auth.password options.
database (String)Specifies which database to connect to and overrides any database specified in the connection string.
replicaSet (String)To connect to a single node replica set, specify the replicaSet option, see Replica Set Host Names
ssl (Boolean)falseFlag to indicate the connection will use SSL
authSource (String)See Replica Set Connections
reconnectTries (Number) (Deprecrated)30000If you're connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every reconnectInterval milliseconds for reconnectTries times, and give up afterward. When the driver gives up, the mongoose connection emits a reconnectFailed event. This option does nothing for replica set connections.
reconnectInterval (Number) (Deprecated)1000See reconnectTries
readPreference (String)secondaryPreferredRead preference describes how MongoDB clients route read operations to the members of a replica set. Possibles values: primary, primaryPreferred, secondary, secondaryPreferred, nearest.
Docs: https://docs.mongodb.com/manual/core/read-preference/

ReadPreference Options

PropertyDescription
primaryAll operations read from the current replica set primary.
primaryPreferredIn most situations, operations read from the primary but if it is unavailable, operations read from secondary members.
secondaryAll operations read from the secondary members of the replica set.
secondaryPreferredIn most situations, operations read from secondary members but if no secondary members are available, operations read from the primary.
nearestOperations read from member of the replica set with the least network latency, irrespective of the member’s type.

In case you want to connect to mongo Atlas via cluster,

  1. You should check the connection metrics of your cluster.You must verify that this is your ip

    Captura de Pantalla 2021-09-29 a la(s) 9 58 37 p  m
  2. Copy the hosts of your metrics and concatenate them in the host property of your connection configuration to mongo example: in its connection parameters. Only the url of this section should be included, separated by commas.

    Captura de Pantalla 2021-09-29 a la(s) 10 20 43 p  m

host: 'cluster0-shard-00-00.ksccs.mongodb.net,cluster0-shard-00-01.ksccs.mongodb.net,cluster0-shard-00-02.ksccs.mongodb.net'

  1. You may have an authentication error, you must verify that your user has read and write permissions. Captura de Pantalla 2021-09-29 a la(s) 10 27 58 p  m

this error may also be due to not adding the authSource attribute in the configuration json.

Example Code

this is an example for multiple connections:

First we are going to create an array of connections

const mongoDbSettings = [
  {
    connectionName: "connection_mongo_1",
    host: "localhost",
    port: 27017,
    database: "development",
    user: "local-user",
    password: "superSecretPass",
    ssl: false,
  },
  {
    connectionName: "connection_mongo_2",
    host: "exapmle-shard-00-00-8burs.mongodb.net,exapmle-shard-00-01-8burs.mongodb.net,exapmle-shard-00-02-8burs.mongodb.net",
    port: 27017,
    database: "dev",
    user: "my-user-2",
    password: "superSecretPass",
    replicaSet: "compliance-support-shard-0",
    ssl: true,
    authSource: "admin",
  },
];

We are going to create a helper (mongoHelper.js) that will included the following logic

"use strict";

const mongo = require("@condor-labs/mongodb")(mongoDbSettings);

const helper = {
  clients: {}, // In clients we will save our connections that the library send us
  isConnected: (connectionName) => {
    return mongo._isConnected(connectionName);
  },
  connect: async () => {
    // It will connect every connection on the array "mongoDbSettings"
    for (const item of mongoDbSettings) {
      let client = await mongo.getClient(item.connectionName);
      helper.clients[item.connectionName] = client;
    }
  },
};

module.exports = helper;

now we are going to create our models

model1.js

const mongodb = require("@condor-labs/mongodb")();
const helperMongo = require("./mongoHelper");

let userSchema = new mongodb.mongoose.Schema({
  user: String,
  token: String,
  password: String,
});

const dbConnection = helperMongo.clients["connection_mongo_1"]; // I got the name of the connection from mongoDbSettings
let userModel = dbConnection.model("User", userSchema); // then I am able to create a my model based on the connection object that I got using my helper

module.exports = userModel;

my sencond model will be similar to the previeus one but instead of using connection_mongo_1 connection I will use connection_mongo_2

model2.js

const mongodb = require("@condor-labs/mongodb")();
const helperMongo = require("./mongoHelper");

let userSchema = new mongodb.mongoose.Schema({
  user: String,
  token: String,
  password: String,
});

const dbConnection = helperMongo.clients["connection_mongo_2"]; // I got the name of the connection from mongoDbSettings
let userModel = dbConnection.model("User", userSchema); // then I am able to create a my model based on the connection object that I got using my helper

module.exports = userModel;

Finallly, after all those configuration we are going to test our connection on our server.js file that includes the following code.

server.js


mongoDbHelper.connect().then(async () => {
  // Load helpers
  const userModelDB1 = require("./model1");
  const userModelDB2 = require("./model2");

  userModelDB1.findOne({}),
  userModelDB2.findOne({}),

})

Contributors

The original author and current lead maintainer of this module is the

Condorlabs Development Team.

More about Condorlabs Here.

License

MIT

Keywords

FAQs

Last updated on 04 Oct 2021

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc