var MongoClient = require('mongodb').MongoClient;
class DAO {
constructor(url, dbName, collectionName) {
this.url = url;
this.dbName = dbName;
this.collectionName = collectionName;
}
_connect () {
return new Promise((resolve, reject) => {
MongoClient.connect(this.url, { useUnifiedTopology: true }, (err, client) => {
if (err) return reject(err);
resolve(client)
})
})
}
insert (obj) {
this._connect().then(client => {
let db = client.db(this.dbName)
db.collection(this.collectionName).insertOne(obj)
client.close()
})
}
}
const dao = new DAO('mongodb://localhost:27017/', 'test', 'user')
let obj = { name: 'xushilin', age: '20' }
dao.insert(obj)
class+promise封装增
最新推荐文章于 2023-07-10 16:21:04 发布