Skip to content

Commit 68b6bbd

Browse files
author
Snowflake107
committed
v2
1 parent 707335e commit 68b6bbd

File tree

8 files changed

+102
-59
lines changed

8 files changed

+102
-59
lines changed

README.md

Lines changed: 25 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,15 @@ Quick mongodb wrapper for beginners.
1010
- Easy
1111
- Simple
1212
- Fast
13+
- Very similar to **[quick.db](https://npmjs.com/package/quick.db)**
14+
- Best alternative to quick.db
15+
- Dot notation support
1316
- Import & export support
1417
- Key value based
15-
- More than 25 methods
18+
- More than 30 methods
1619
- Beginner friendly
17-
18-
> Btw, `quick.db` users can easily export their data to `quickmongo`.
20+
- Asynchronous
21+
- Multiple model/schema support
1922

2023
# Quick Example
2124

@@ -46,7 +49,7 @@ function exportData() {
4649
});
4750
}
4851

49-
exportData();
52+
mongo.on("ready", () => exportData());
5053
```
5154

5255
# Exporting data from quick.db tables (and custom schema names)
@@ -56,7 +59,8 @@ const db = require("quick.db");
5659
const table = new db.table("mytable");
5760

5861
const { Database } = require("quickmongo");
59-
const mongo = new Database("mongodb://localhost/quickmongo", "mytable"); // custom schema name (acts like quickdb table)
62+
const mdb = new Database("mongodb://localhost/quickmongo");
63+
const mongo = mdb.table("mytable"); // custom schema/model, (acts like quickdb table) with all the features of main Database
6064

6165
function exportData() {
6266
const data = table.all();
@@ -65,7 +69,22 @@ function exportData() {
6569
});
6670
}
6771

68-
exportData();
72+
mdb.on("ready", () => exportData());
73+
```
74+
75+
# Exporting data from QuickMongo to QuickDB
76+
77+
```js
78+
const db = require("quick.db");
79+
const { Database } = require("quickmongo");
80+
const mdb = new Database("mongodb://localhost/quickmongo");
81+
82+
mdb.on("ready", () => exportData());
83+
84+
function exportData() {
85+
mdb.exportToQuickDB(db)
86+
.then(console.log);
87+
}
6988
```
7089

7190
# Links
@@ -109,22 +128,4 @@ db.export("rawdata").then(path => {
109128
db.import(quickdb.all()).then(() => {
110129
console.log("Data imported!");
111130
});
112-
```
113-
114-
# Value Targets (Path)
115-
Value target (Like `key.target` of `quick.db`) support is not yet available in this package. It will be available soon :)
116-
117-
But you can still use it like this:
118-
119-
```js
120-
const { Database } = require("quickmongo");
121-
const db = new Database("mongodb://localhost/quickmongo");
122-
123-
// set data
124-
db.set("user", { items: [] });
125-
126-
// update items
127-
let data = await db.get("user");
128-
data.items = ["keyboard"];
129-
db.set("user", data); // { items: ["keyboard"] }
130131
```

index.d.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ export class Database extends Base {
9696
public subtract(key: string, value: number): Promise<any>;
9797
public get uptime(): number;
9898
public export(fileName?: string, path?: string): Promise<string>;
99-
public import(data?: any[], ordered?: boolean): Promise<void>;
99+
public import(data?: DataSet[], ops?: { overwriteExisting?: boolean, validate?: boolean }): Promise<boolean>;
100100
public disconnect(): Promise<void>;
101101
public connect(url: string): Promise<void>;
102102
public get name(): string;
@@ -125,6 +125,7 @@ export class Database extends Base {
125125
public entries(): Promise<number>;
126126
public raw(params?: Mongoose.QueryFindOptions): Promise<Mongoose.Document>;
127127
public random(limit?: number): Promise<DataSet[]>;
128+
public table(name: string): Database;
128129
public exportToQuickDB(): Promise<DataSet[]>;
129130
public get utils(): Util;
130131
public toString(): string;

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "quickmongo",
3-
"version": "1.1.5",
3+
"version": "2.0.0",
44
"description": "Quick mongodb wrapper for beginners.",
55
"main": "index.js",
66
"types": "index.d.ts",

src/Base.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ class Base extends EventEmitter {
4949
* @ignore
5050
*/
5151
_create(url) {
52+
// do not create multiple connections
53+
if (mongoose.connection.readyState) return;
5254
this.emit("debug", "Creating database connection...");
5355
if (url && typeof url === "string") this.dbURL = url;
5456
if (!this.dbURL || typeof this.dbURL !== "string") throw new Error("Database url was not provided!", "MongoError");

src/Error.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ class QuickError extends Error {
44
super();
55
Error.captureStackTrace(this, this.constructor);
66
this.message = message;
7-
this.name = name || "QuickMongoError";
7+
this.name = name || "TypeError";
88
}
99

1010
}

src/Main.js

Lines changed: 63 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -36,21 +36,22 @@ class Database extends Base {
3636
async set(key, value) {
3737
if (!Util.isKey(key)) throw new Error("Invalid key specified!", "KeyError");
3838
if (!Util.isValue(value)) throw new Error("Invalid value specified!", "ValueError");
39+
const parsed = Util.parseKey(key);
3940
let raw = await this.schema.findOne({
40-
ID: key
41+
ID: parsed.key
4142
});
4243
if (!raw) {
4344
let data = new this.schema({
44-
ID: key,
45-
data: value
45+
ID: parsed.key,
46+
data: parsed.target ? Util.setData(key, {}, value) : value
4647
});
4748
await data.save()
4849
.catch(e => {
4950
return this.emit("error", e);
5051
});
5152
return data.data;
5253
} else {
53-
raw.data = value;
54+
raw.data = parsed.target ? Util.setData(key, Object.assign({}, raw.data), value) : value;
5455
await raw.save()
5556
.catch(e => {
5657
return this.emit("error", e);
@@ -66,11 +67,21 @@ class Database extends Base {
6667
*/
6768
async delete(key) {
6869
if (!Util.isKey(key)) throw new Error("Invalid key specified!", "KeyError");
69-
let data = await this.schema.findOneAndDelete({ ID: key })
70-
.catch(e => {
71-
return this.emit("error", e);
72-
});
73-
return data;
70+
const parsed = Util.parseKey(key);
71+
const raw = await this.schema.findOne({ ID: parsed.key });
72+
if (!raw) return false;
73+
if (parsed.target) {
74+
let data = Util.unsetData(key, Object.assign({}, raw.data));
75+
raw.data = data;
76+
raw.save().catch(e => this.emit("error", e));
77+
return data;
78+
} else {
79+
let data = await this.schema.findOneAndDelete({ ID: parsed.key })
80+
.catch(e => {
81+
return this.emit("error", e);
82+
});
83+
return data;
84+
}
7485
}
7586

7687
/**
@@ -100,12 +111,17 @@ class Database extends Base {
100111
*/
101112
async get(key) {
102113
if (!Util.isKey(key)) throw new Error("Invalid key specified!", "KeyError");
103-
let get = await this.schema.findOne({ ID: key })
114+
const parsed = Util.parseKey(key);
115+
116+
let get = await this.schema.findOne({ ID: parsed.key })
104117
.catch(e => {
105118
return this.emit("error", e);
106119
});
107120
if (!get) return null;
108-
return get.data;
121+
let item;
122+
if (parsed.target) item = Util.getData(key, Object.assign({}, get.data));
123+
else item = get.data;
124+
return item ? item : null;
109125
}
110126

111127
/**
@@ -285,19 +301,32 @@ class Database extends Base {
285301
* [{ ID: "foo", data: "bar" }, { ID: "hi", data: "hello" }]
286302
* ```
287303
* @param {Array} data Array of data
288-
* @param {boolean} ordered If set to false, it will insert valid documents before throwing errors (if any)
304+
* @param {object} ops Import options
305+
* @param {boolean} [ops.validate=false] If set to true, it will insert valid documents only
306+
* @param {boolean} [ops.overwriteExisting=false] If it should overwrite existing value (slow)
289307
* @example const data = QuickDB.all(); // imports data from quick.db to quickmongo
290308
* QuickMongo.import(data);
291309
* @returns {Promise<Boolean>}
292310
*/
293-
import(data=[], ordered = true) {
294-
return new Promise((resolve, reject) => {
311+
import(data=[], ops = { overwriteExisting: false, validate: false }) {
312+
return new Promise(async (resolve, reject) => {
295313
if (!Array.isArray(data)) return reject(new Error(`Data type must be Array, received ${typeof data}!`, "DataTypeError"));
296314
if (data.length < 1) return resolve(false);
297-
this.schema.insertMany(data, { ordered: !!ordered }, (error) => {
298-
if (error) return reject(new Error(`${error}`, "DataImportError"));
315+
if (!ops.overwriteExisting) {
316+
this.schema.insertMany(data, { ordered: !ops.validate }, (error) => {
317+
if (error) return reject(new Error(`${error}`, "DataImportError"));
318+
return resolve(true);
319+
});
320+
} else {
321+
data.forEach((x, i) => {
322+
if (!ops.validate && (!x.ID || !x.data)) return;
323+
else if (!!ops.validate && (!x.ID || !x.data)) return reject(new Error(`Data is missing ${!x.ID ? "ID" : "data"} path!`, "DataImportError"));
324+
setTimeout(() => {
325+
this.set(x.ID, x.data);
326+
}, 457 * (i + 1));
327+
});
299328
return resolve(true);
300-
});
329+
}
301330
});
302331
}
303332

@@ -481,20 +510,27 @@ class Database extends Base {
481510

482511
/**
483512
* Returns random entry from the database
484-
* @param {number} total total entries to return
513+
* @param {number} n Number entries to return
485514
* @returns {Promise<any[]>}
486515
* @example const random = await db.random();
487516
* console.log(random);
488517
*/
489-
async random(total = 1) {
490-
if (typeof total !== "number" || total < 1) total = 1;
518+
async random(n = 1) {
519+
if (typeof n !== "number" || n < 1) n = 1;
491520
const data = await this.all();
492-
const arr = [];
493-
for (let i = 0; i < total; i++) {
494-
const entry = data[Math.floor(Math.random() * data.length)];
495-
if (!arr.includes(entry)) arr.push(entry);
496-
}
497-
return arr;
521+
if (n > data.length) throw new RangeError("Random value length may not exceed total length.");
522+
const shuffled = data.sort(() => 0.5 - Math.random());
523+
return shuffled.slice(0, n);
524+
}
525+
526+
/**
527+
* This method acts like `quick.db#table`. It will return new instance of itself.
528+
* @param {string} name Schema/Model name
529+
*/
530+
table(name) {
531+
if (!name || typeof name !== "string") throw new Error("Invalid model name");
532+
const CustomModel = new Database(this.dbURL, name, this.options);
533+
return CustomModel;
498534
}
499535

500536
/**
@@ -526,7 +562,7 @@ class Database extends Base {
526562
* @example console.log(db.toString());
527563
*/
528564
toString() {
529-
return `<${this.constructor.name} QuickMongo>`;
565+
return `${this.schema.modelName}`;
530566
}
531567

532568
/**

src/Util.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ class Util {
7777
let parsed = this.parseKey(key);
7878
if (typeof data === "object" && parsed.target) {
7979
return _.set(data, parsed.target, value);
80-
} else if (parsed.target) throw new Error("Cannot target non-object.", "SyntaxError");
80+
} else if (parsed.target) throw new Error("Cannot target non-object.", "TargetError");
8181
return data;
8282
}
8383

@@ -93,7 +93,7 @@ class Util {
9393
let item = data;
9494
if (typeof data === "object" && parsed.target) {
9595
_.unset(item, parsed.target);
96-
} else if (parsed.target) throw new Error("Cannot target non-object.", "SyntaxError");
96+
} else if (parsed.target) throw new Error("Cannot target non-object.", "TargetError");
9797
return item;
9898
}
9999

test/test.js

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
const { Database } = require("../index");
22
const db = new Database("mongodb://localhost/test");
33

4-
db.on("ready", () => {
5-
console.log("Hey, im connected!");
6-
db.set("foo", "bar").then(() => db.export("./database.json"))
4+
db.on("ready", async () => {
5+
console.log(`Hey, im connected! ${db.toString()}`);
6+
console.log(await db.all(), `${db}`);
7+
8+
const mydb = db.table("TEST");
9+
console.log(await mydb.all(), `${mydb}`);
710
});
811

912
db.on("error", console.error);

0 commit comments

Comments
 (0)