const Config = require("./config");
const MongoClient = require("mongodb").MongoClient;
const client = new MongoClient(Config.dbUrl, { useUnifiedTopology: true });
class Db {
constructor() {
// this.connect();
}
async connect() {
try {
await client.connect();
return client.db(Config.dbName);
} catch (e) {
throw new Error(e);
}
}
async find(collectionName, json) {
try {
const db = await this.connect();
const collection = db.collection(collectionName);
const docs = await collection.find(json).toArray();
return docs;
} catch (e) {
throw new Error(e);
}
}
}
const db = new Db();
(async () => {
try {
const docs = await db.find("student", {});
console.log(docs);
} catch (e) {
console.log(e.message);
}
})();
const Config = require("./config");
const MongoClient = require("mongodb").MongoClient;
const client = new MongoClient(Config.dbUrl, { useUnifiedTopology: true });
class Db {
constructor() {
// this.connect();
}
connect() {
return new Promise((resolve, reject) => {
client.connect(err => {
if (err) {
reject(err);
} else {
const db = client.db(Config.dbName);
resolve(db);
}
});
});
}
find(collectionName, json) {
return new Promise((resolve, reject) => {
this.connect()
.then(db => {
const collection = db.collection(collectionName);
collection.find(json).toArray((err, docs) => {
if (err) {
reject(err);
} else {
resolve(docs);
}
});
})
.catch(e => {
reject(e)
});
});
}
}
const db = new Db();
db.find("student", {})
.then(docs => {
console.log(docs);
})
.catch(e => {
console.log(e.message);
});
网友评论