mongoplusplus 1.0.4 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,170 +1,188 @@
1
- # mongoplusplus
2
-
3
- ## Overview
4
-
5
- `mongoplusplus` is a Node.js package designed to facilitate load balancing of read and write operations across multiple MongoDB databases. It simplifies database connection management, schema definition, model building, and CRUD operations execution.
6
-
7
- ## Installation
8
-
9
- Install mongoplusplus via npm:
10
-
11
- ```bash
12
- npm install mongoplusplus
13
- ```
14
-
15
- importing
16
- ```node
17
- const mongoplusplus = require('mongoplusplus');
18
- ```
19
- ##Initialing
20
- ```node
21
- const dbname = 'testforUP';
22
-
23
- const mongoURI1 = `mongodb+srv://xxxxx:xxxxxx@cluster0.xxxxx.mongodb.net/${dbname}?retryWrites=true&w=majority`;
24
- const mongoURI2 = `readonly:mongodb+srv://xxxxxxx:xxxxxx@cluster0.xxxxxx.mongodb.net/${dbname}?retryWrites=true&w=majority`;
25
- const mongodb = new mongoplusplus([mongoURI1, mongoURI2]);
26
-
27
- ```
28
- ##connecting database
29
- this is the top level thing in your main page (in this test code, under mongodb variable declaration )
30
- ```node
31
- (async () => {
32
- await mongodb.connectToAll();
33
- })();
34
- ```
35
- ##Schema defining
36
- it is very similar to Mongoose schema definition.but only one mandatory field must be there in the schema which will act as a db identifier for that document
37
- ```node
38
- const likeSH = mongodb.Schema({
39
- user_id: { type: mongoose.Schema.Types.ObjectId, required: true, ref: "users" },
40
- postId: { type: mongoose.Schema.Types.ObjectId, required: true },
41
- dbIndex: { type: Number, required: true },
42
-
43
- like_time: { type: Date, default: Date.now }
44
- }
45
- )
46
- ```
47
- ### model building
48
- ```node
49
- const likes = mongodb.buildModel("likes", likeSH)
50
- ```
51
-
52
-
53
- ##### Note that `dbIndex` is used to indicate which MongoDB server it belongs to.
54
- ###### it is a must otherwise it will throw an error.
55
- ```node
56
- throw new Error(`[!]Error : < dbIndex > must be present in your schema like dbIndex:{
57
- type: Number,
58
- required: true
59
- } `)
60
- ```
61
-
62
-
63
- ### usage methods
64
- ```node
65
- findInAllDatabase(filter, chain = {})
66
- ```
67
- Usage: Finds documents matching the filter in all MongoDB databases.
68
-
69
- ```node
70
- const result = await likes.findInAllDatabase({ name: 'John' }, { limit: 10, skip: 0 });
71
- Returns: An array of documents matching the filter from all databases.
72
- ```
73
- ```node
74
- writeInAllDatabase(data)
75
-
76
- Usage: Writes data to all MongoDB databases.
77
-
78
- const result = await likes.writeInAllDatabase({ name: 'John', age: 30 });
79
- Returns: An array of written documents from all databases.
80
- ```
81
- ```node
82
- UpdateOneInAllDatabase(filter, update)
83
- Usage: Updates a single document matching the filter in all MongoDB databases.
84
- const updatedDocument = await likes.UpdateOneInAllDatabase({ name: 'John' }, { age: 35 });
85
- Returns: The updated document.
86
- ```
87
- ```node
88
- UpdateByIdInAllDatabase(id, update)
89
- Usage: Updates a document by ID in all MongoDB databases.
90
- const updatedDocument = await likes.UpdateByIdInAllDatabase('123456', { age: 35 });
91
- Returns: The updated document.
92
- ```
93
- ```node
94
- findByIdInAllDatabaseAndDelete(id)
95
- Usage: Finds a document by ID in all MongoDB databases and deletes it.
96
- const deletedDocument = await likes.findByIdInAllDatabaseAndDelete('123456');
97
- Returns: The deleted document.
98
- ```
99
-
100
- ```node
101
- findOneInAllDatabaseAndDelete(filter)
102
- Usage: Finds a single document matching the filter in all MongoDB databases and deletes it.
103
- const deletedDocument = await likes.findOneInAllDatabaseAndDelete({ name: 'John' });
104
- Returns: The deleted document.
105
- ```
106
- ```node
107
- write(data)
108
- Usage: Writes data to a MongoDB database.
109
- const result = await likes.write({ name: 'John', age: 30 });
110
- Returns: The written document.
111
- ```
112
-
113
- ```node
114
- findOne(dbIndex, filter, chain = {})
115
- Usage: Finds a single document matching the filter in a specific MongoDB database.
116
- const document = await likes.findOne(0, { name: 'John' }, { limit: 1 });
117
- Returns: The found document.
118
- ```
119
- ```node
120
- find(dbIndex, filter, chain = {})
121
- Usage: Finds documents matching the filter in a specific MongoDB database.
122
- const documents = await likes.find(0, { age: { $gt: 18 } }, { limit: 10 });
123
- Returns: An array of found documents.
124
- ```
125
-
126
- ```node
127
- findById(dbIndex, id, chain = {})
128
- Usage: Finds a document by ID in a specific MongoDB database.
129
- const document = await likes.findById(0, '123456');
130
- Returns: The found document.
131
- ```
132
- ```node
133
- findByIdAndUpdate(dbIndex, id, update)
134
- Usage: Finds a document by ID in a specific MongoDB database and updates it.
135
- const updatedDocument = await likes.findByIdAndUpdate(0, '123456', { age: 35 });
136
- Returns: The updated document.
137
- ```
138
- ```node
139
- findByIdAndDelete(dbIndex, id)
140
- Usage: Finds a document by ID in a specific MongoDB database and deletes it.
141
- const deletedDocument = await likes.findByIdAndDelete(0, '123456');
142
- Returns: The deleted document.
143
- ```
144
- ```node
145
- findOneAndUpdate(dbIndex, filter, update)
146
- Usage: Finds a single document matching the filter in a specific MongoDB database and updates it.
147
-
148
- const updatedDocument = await likes.findOneAndUpdate(0, { name: 'John' }, { age: 35 });
149
- Returns: The updated document.
150
- ```
151
- ```node
152
- aggregate(dbIndex, filter)
153
- Usage: Aggregates documents in a specific MongoDB database based on the filter.
154
- const aggregationResult = await likes.aggregate(0, [{ $group: { _id: '$name', total: { $sum: '$age' } } }]);
155
- Returns: The aggregation result.
156
- ```
157
- ```node
158
- watch(dbIndex)
159
- Usage: Starts watching for changes in a specific MongoDB database.
160
- const watcher = await likes.watch(0);
161
- Returns: A watcher object for the database.
162
- ```
163
-
164
- > now most of the functionality is as same as mongoose so you can use them directly like indexing a schema
165
- ```node
166
- likeSH.index({ user_id: 1, postId: 1 }, { unique: true });
167
- ```
168
- # Contributing
169
- there are many things that are not ported. feel free to contribute!
1
+ # mongoplusplus
2
+
3
+ ## Overview
4
+
5
+ `mongoplusplus` is a Node.js package designed to facilitate load balancing of read and write operations across multiple MongoDB databases. It simplifies database connection management, schema definition, model building, and CRUD operations execution.
6
+
7
+ ## Installation
8
+
9
+ Install mongoplusplus via npm:
10
+
11
+ ```bash
12
+ npm install mongoplusplus
13
+ ```
14
+
15
+ importing
16
+ ```node
17
+ const mongoplusplus = require('mongoplusplus');
18
+ ```
19
+ ##Initialing
20
+ ```node
21
+ const dbname = 'testforUP';
22
+
23
+ const mongoURI1 = `mongodb+srv://xxxxx:xxxxxx@cluster0.xxxxx.mongodb.net/${dbname}?retryWrites=true&w=majority`;
24
+ const mongoURI2 = `readonly:mongodb+srv://xxxxxxx:xxxxxx@cluster0.xxxxxx.mongodb.net/${dbname}?retryWrites=true&w=majority`;
25
+ const mongodb = new mongoplusplus([mongoURI1, mongoURI2]);
26
+
27
+ ```
28
+ ##connecting database
29
+ this is the top level thing in your main page (in this test code, under mongodb variable declaration )
30
+ ```node
31
+ (async () => {
32
+ await mongodb.connectToAll();
33
+ })();
34
+ ```
35
+ ##Schema defining
36
+ it is very similar to Mongoose schema definition.but only one mandatory field must be there in the schema which will act as a db identifier for that document
37
+ ```node
38
+ const likeSH = mongodb.Schema({
39
+ user_id: { type: mongoose.Schema.Types.ObjectId, required: true, ref: "users" },
40
+ postId: { type: mongoose.Schema.Types.ObjectId, required: true },
41
+ dbIndex: { type: Number, required: true },
42
+
43
+ like_time: { type: Date, default: Date.now }
44
+ }
45
+ )
46
+ ```
47
+ ### model building
48
+ ```node
49
+ const likes = mongodb.buildModel("likes", likeSH)
50
+ ```
51
+
52
+
53
+ ##### Note that `dbIndex` is used to indicate which MongoDB server it belongs to.
54
+ ###### it is a must otherwise it will throw an error.
55
+ ```node
56
+ throw new Error(`[!]Error : < dbIndex > must be present in your schema like dbIndex:{
57
+ type: Number,
58
+ required: true
59
+ } `)
60
+ ```
61
+
62
+
63
+ ### usage methods
64
+ ```node
65
+ findInAllDatabase(filter, chain = {})
66
+ ```
67
+ Usage: Finds documents matching the filter in all MongoDB databases.
68
+
69
+ ```node
70
+ const result = await likes.findInAllDatabase({ name: 'John' }, { limit: 10, skip: 0 });
71
+ Returns: An array of documents matching the filter from all databases.
72
+ ```
73
+ ```node
74
+ writeInAllDatabase(data)
75
+
76
+ Usage: Writes data to all MongoDB databases.
77
+
78
+ const result = await likes.writeInAllDatabase({ name: 'John', age: 30 });
79
+ Returns: An array of written documents from all databases.
80
+ ```
81
+ ```node
82
+ UpdateOneInAllDatabase(filter, update)
83
+ Usage: Updates a single document matching the filter in all MongoDB databases.
84
+ const updatedDocument = await likes.UpdateOneInAllDatabase({ name: 'John' }, { age: 35 });
85
+ Returns: The updated document.
86
+ ```
87
+ ```node
88
+ UpdateByIdInAllDatabase(id, update)
89
+ Usage: Updates a document by ID in all MongoDB databases.
90
+ const updatedDocument = await likes.UpdateByIdInAllDatabase('123456', { age: 35 });
91
+ Returns: The updated document.
92
+ ```
93
+ ```node
94
+ findByIdInAllDatabaseAndDelete(id)
95
+ Usage: Finds a document by ID in all MongoDB databases and deletes it.
96
+ const deletedDocument = await likes.findByIdInAllDatabaseAndDelete('123456');
97
+ Returns: The deleted document.
98
+ ```
99
+
100
+ ```node
101
+ findOneInAllDatabaseAndDelete(filter)
102
+ Usage: Finds a single document matching the filter in all MongoDB databases and deletes it.
103
+ const deletedDocument = await likes.findOneInAllDatabaseAndDelete({ name: 'John' });
104
+ Returns: The deleted document.
105
+ ```
106
+ ```node
107
+ write(data)
108
+ Usage: Writes data to a MongoDB database.
109
+ const result = await likes.write({ name: 'John', age: 30 });
110
+ Returns: The written document.
111
+ ```
112
+
113
+ ```node
114
+ bulkWrite(data)
115
+ Usage: Bulk writes data to a MongoDB database with transaction inbuilt.
116
+
117
+ const testData = Array.from({ length: 10000 }, (_, i) => ({
118
+ name: `User ${i}`,
119
+ email: `user${i}@example.com`,
120
+ age: 20 + (i % 50)
121
+ }));
122
+
123
+ // Test 1: Large batch, concurrent
124
+ console.time('Large batch concurrent');
125
+ await UserModel.bulkWrite(testData, {
126
+ batchSize: 5000,
127
+ concurrentBatches: true
128
+ });
129
+ ```
130
+
131
+ ```node
132
+ findOne(dbIndex, filter, chain = {})
133
+ Usage: Finds a single document matching the filter in a specific MongoDB database.
134
+ const document = await likes.findOne(0, { name: 'John' }, { limit: 1 });
135
+ Returns: The found document.
136
+ ```
137
+ ```node
138
+ find(dbIndex, filter, chain = {})
139
+ Usage: Finds documents matching the filter in a specific MongoDB database.
140
+ const documents = await likes.find(0, { age: { $gt: 18 } }, { limit: 10 });
141
+ Returns: An array of found documents.
142
+ ```
143
+
144
+ ```node
145
+ findById(dbIndex, id, chain = {})
146
+ Usage: Finds a document by ID in a specific MongoDB database.
147
+ const document = await likes.findById(0, '123456');
148
+ Returns: The found document.
149
+ ```
150
+ ```node
151
+ findByIdAndUpdate(dbIndex, id, update)
152
+ Usage: Finds a document by ID in a specific MongoDB database and updates it.
153
+ const updatedDocument = await likes.findByIdAndUpdate(0, '123456', { age: 35 });
154
+ Returns: The updated document.
155
+ ```
156
+ ```node
157
+ findByIdAndDelete(dbIndex, id)
158
+ Usage: Finds a document by ID in a specific MongoDB database and deletes it.
159
+ const deletedDocument = await likes.findByIdAndDelete(0, '123456');
160
+ Returns: The deleted document.
161
+ ```
162
+ ```node
163
+ findOneAndUpdate(dbIndex, filter, update)
164
+ Usage: Finds a single document matching the filter in a specific MongoDB database and updates it.
165
+
166
+ const updatedDocument = await likes.findOneAndUpdate(0, { name: 'John' }, { age: 35 });
167
+ Returns: The updated document.
168
+ ```
169
+ ```node
170
+ aggregate(dbIndex, filter)
171
+ Usage: Aggregates documents in a specific MongoDB database based on the filter.
172
+ const aggregationResult = await likes.aggregate(0, [{ $group: { _id: '$name', total: { $sum: '$age' } } }]);
173
+ Returns: The aggregation result.
174
+ ```
175
+ ```node
176
+ watch(dbIndex)
177
+ Usage: Starts watching for changes in a specific MongoDB database.
178
+ const watcher = await likes.watch(0);
179
+ Returns: A watcher object for the database.
180
+ ```
181
+
182
+ > now most of the functionality is as same as mongoose so you can use them directly like indexing a schema
183
+ ```node
184
+ likeSH.index({ user_id: 1, postId: 1 }, { unique: true });
185
+ ```
186
+ # Contributing
187
+ there are many things that are not ported. feel free to contribute!
170
188
  Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. Please make sure to update.and also
package/index.d.ts ADDED
@@ -0,0 +1,226 @@
1
+ import * as mongoose from 'mongoose';
2
+
3
+ /**
4
+ * Mongoplus manages multiple mongoose connections and builds distributed models.
5
+ *
6
+ * Example:
7
+ * ```ts
8
+ * import Mongoplus from 'mongoplusplus';
9
+ * const mp = new Mongoplus(['mongodb://a/db','readonly:mongodb://b/db']);
10
+ * await mp.connectToAll();
11
+ * ```
12
+ */
13
+ declare class Mongoplus {
14
+ /** Array of connection URIs. Use `readonly:` prefix to mark read-only URIs. */
15
+ mongoURI: string[];
16
+ /** All mongoose connections created by `connectToAll`. */
17
+ allConnections: mongoose.Connection[];
18
+ /** Internal rotation index. */
19
+ currentIndex: number;
20
+ /** Connections created from `readonly:` URIs. */
21
+ static readonlydbs: mongoose.Connection[];
22
+ /** Models corresponding to readonly connections. */
23
+ static readonlymodels: any[];
24
+
25
+ /**
26
+ * Create manager with list of URIs.
27
+ * @example
28
+ * const mp = new Mongoplus(['mongodb://a/db','readonly:mongodb://b/db']);
29
+ */
30
+ constructor(mongoURI: string[]);
31
+
32
+ /**
33
+ * Create a mongoose Schema.
34
+ * @example
35
+ * const schema = mp.Schema({ name: String, dbIndex: { type: Number, required: true } });
36
+ */
37
+ Schema(schema: mongoose.SchemaDefinition | mongoose.Schema): mongoose.Schema;
38
+
39
+ /**
40
+ * Add an index to a schema.
41
+ * @example
42
+ * mp.addIndex(schema, { email: 1 });
43
+ */
44
+ addIndex(schema: mongoose.Schema, indextype: any): void;
45
+
46
+ /**
47
+ * Return next MongoDB URI in rotation.
48
+ */
49
+ getNextMongoURI(): string;
50
+
51
+ /**
52
+ * Establish all connections. Call before `buildModel`.
53
+ * @returns array of `mongoose.Connection`.
54
+ */
55
+ connectToAll(): mongoose.Connection[];
56
+
57
+ /**
58
+ * Build a distributed model across all connections. Schema must include `dbIndex`.
59
+ * @example
60
+ * const User = mp.buildModel('User', schema);
61
+ */
62
+ buildModel(name: string, schema: mongoose.Schema): MongoModel;
63
+ }
64
+
65
+ /**
66
+ * MongoModel wraps per-connection models and exposes multi-DB helpers.
67
+ */
68
+ declare class MongoModel {
69
+ /** Per-connection mongoose Model instances. */
70
+ model: any[];
71
+ /** Read-only model references. */
72
+ readonlydbs: any[];
73
+ /** Original schema. */
74
+ s: mongoose.Schema;
75
+ /** Rotation index for `write`. */
76
+ static currentIndex: number;
77
+
78
+ /**
79
+ * Construct a MongoModel.
80
+ * @example
81
+ * const mm = new MongoModel([M1,M2], schema, [M2]);
82
+ */
83
+ constructor(model: any[], s: mongoose.Schema, readonlydbs: any[]);
84
+
85
+ /**
86
+ * Run `find` on every DB and return aggregated results with timing.
87
+ * @example
88
+ * const { results, totalTime } = await User.findInAllDatabase({ active: true });
89
+ */
90
+ findInAllDatabase(filter: any, chain?: any): Promise<any>;
91
+
92
+ /**
93
+ * Run aggregation pipeline on every DB and return aggregated results.
94
+ * @example
95
+ * await User.aggregateInAllDatabase([{ $match: { age: { $gt: 18 } } }]);
96
+ */
97
+ aggregateInAllDatabase(filter: any, chain?: any): Promise<any>;
98
+
99
+ /**
100
+ * Write the same document to all writable DBs. Returns saved docs array.
101
+ * @example
102
+ * await User.writeInAllDatabase({ name: 'Alice' });
103
+ */
104
+ writeInAllDatabase(data: any): Promise<any[]>;
105
+
106
+ /**
107
+ * Update one matching document across all DBs.
108
+ * @example
109
+ * await User.UpdateOneInAllDatabase({ active: false }, { active: true });
110
+ */
111
+ UpdateOneInAllDatabase(filter: any, update: any): Promise<any>;
112
+
113
+ /**
114
+ * Update by id across all DBs.
115
+ * @example
116
+ * await User.UpdateByIdInAllDatabase(id, { name: 'Bob' });
117
+ */
118
+ UpdateByIdInAllDatabase(id: any, update: any): Promise<any>;
119
+
120
+ /**
121
+ * Find by id in all DBs and delete.
122
+ * @example
123
+ * await User.findByIdInAllDatabaseAndDelete(id);
124
+ */
125
+ findByIdInAllDatabaseAndDelete(id: any): Promise<any>;
126
+
127
+ /**
128
+ * Find one in all DBs and delete.
129
+ * @example
130
+ * await User.findOneInAllDatabaseAndDelete({ email: 'x@example.com' });
131
+ */
132
+ findOneInAllDatabaseAndDelete(filter: any): Promise<any>;
133
+
134
+ /**
135
+ * Delete many documents matching `filter` in all databases and return aggregated results.
136
+ * @example
137
+ * await User.finManyInAllDatabaseAndDelete({ expired: true });
138
+ */
139
+ findManyInAllDatabaseAndDelete(filter: any): Promise<any>;
140
+
141
+ /**
142
+ * Write a single document using round-robin balancing across writable DBs.
143
+ * @example
144
+ * const saved = await User.write({ name: 'Charlie' });
145
+ */
146
+ write(data: any): Promise<any>;
147
+
148
+ /**
149
+ * Perform efficient bulk upserts across writable DBs.
150
+ * @example
151
+ * await User.bulkWrite([{ id: '1', name: 'A' }], { batchSize: 500 });
152
+ */
153
+ bulkWrite(data: any[], options?: { batchSize?: number; concurrentBatches?: boolean }): Promise<any[]>;
154
+
155
+ /**
156
+ * Find a single document on a specific DB index.
157
+ * @example
158
+ * await User.findOne(0, { email: 'x' });
159
+ */
160
+ findOne(dbIndex: number, filter: any, chain?: any): Promise<any>;
161
+
162
+ /**
163
+ * Find documents on a specific DB index.
164
+ * @example
165
+ * await User.find(1, { active: true }, { limit: 10 });
166
+ */
167
+ find(dbIndex: number, filter: any, chain?: any): Promise<any>;
168
+
169
+ /**
170
+ * Find by id on a specific DB index.
171
+ * @example
172
+ * await User.findById(0, id);
173
+ */
174
+ findById(dbIndex: number, filter: any, chain?: any): Promise<any>;
175
+
176
+ /**
177
+ * Find by id and update on a specific DB index.
178
+ * @example
179
+ * await User.findByIdAndUpdate(0, id, { name: 'New' });
180
+ */
181
+ findByIdAndUpdate(dbIndex: number, id: any, update: any): Promise<any>;
182
+
183
+ /**
184
+ * Find by id and delete on a specific DB index.
185
+ * @example
186
+ * await User.findByIdAndDelete(1, id);
187
+ */
188
+ findByIdAndDelete(dbIndex: number, id: any, update?: any): Promise<any>;
189
+
190
+ /**
191
+ * Find one and update on a specific DB index.
192
+ * @example
193
+ * await User.findOneAndUpdate(0, { email: 'x' }, { active: false });
194
+ */
195
+ findOneAndUpdate(dbIndex: number, filter: any, update: any): Promise<any>;
196
+
197
+ /**
198
+ * Run aggregation on a specific DB index.
199
+ * @example
200
+ * await User.aggregate(0, [{ $group: { _id: '$country', count: { $sum: 1 } } }]);
201
+ */
202
+ aggregate(dbIndex: number, filter: any): Promise<any>;
203
+
204
+ /**
205
+ * Watch change stream on a specific DB index.
206
+ * @example
207
+ * const stream = User.watch(0);
208
+ */
209
+ watch(dbIndex: number): any;
210
+
211
+ /**
212
+ * Return the next model and its index for round-robin writes.
213
+ * @example
214
+ * const [model, idx] = User.getNextModel();
215
+ */
216
+ getNextModel(): [any, number];
217
+
218
+ /**
219
+ * Internal runner to execute many queries concurrently and return results with timing.
220
+ */
221
+ runLargeComputations(computationPairs: any[]): Promise<{ results: any[]; totalTime: number }>;
222
+ }
223
+
224
+ export default Mongoplus;
225
+ export { MongoModel };
226
+