
Promise 是一个 ECMAScript 6 提供的类,目的是更加优雅地书写复杂的异步任务。
如果你还不了解 Promise,可以参考 JavaScript Promise。
以下实例使用 Promise 创建集合:
const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://localhost/runoob";
MongoClient.connect(url).then((conn) => {
console.log("数据库已连接");
var dbase = conn.db("runoob");
dbase.createCollection("site").then((res) => {
console.log("已创建集合");
}).catch((err) => {
console.log("数据库操作错误");
}).finally(() => {
conn.close();
});
}).catch((err) => {
console.log("数据库连接失败");
});现在我们在一个程序中实现四个连续操作:增加 、查询 、更改 、删除。
const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://localhost/";
MongoClient.connect(url).then((conn) => {
console.log("数据库已连接");
const test = conn.db("testdb").collection("test");
// 增加
test.insertOne({ "site": "runoob.com" }).then((res) => {
// 查询
return test.find().toArray().then((arr) => {
console.log(arr);
});
}).then(() => {
// 更改
return test.updateMany({ "site": "runoob.com" },
{ $set: { "site": "example.com" } });
}).then((res) => {
// 查询
return test.find().toArray().then((arr) => {
console.log(arr);
});
}).then(() => {
// 删除
return test.deleteMany({ "site": "example.com" });
}).then((res) => {
// 查询
return test.find().toArray().then((arr) => {
console.log(arr);
});
}).catch((err) => {
console.log("数据操作失败" + err.message);
}).finally(() => {
conn.close();
});
}).catch((err) => {
console.log("数据库连接失败");
});执行结果:
数据库已连接
[ { _id: 5f1664966833e531d83d3ac6, site: 'runoob.com' } ]
[ { _id: 5f1664966833e531d83d3ac6, site: 'example.com' } ]
[]const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://localhost/";
async function dataOperate() {
var conn = null;
try {
conn = await MongoClient.connect(url);
console.log("数据库已连接");
const test = conn.db("testdb").collection("test");
// 增加
await test.insertOne({ "site": "runoob.com" });
// 查询
var arr = await test.find().toArray();
console.log(arr);
// 更改
await test.updateMany({ "site": "runoob.com" },
{ $set: { "site": "example.com" } });
// 查询
arr = await test.find().toArray();
console.log(arr);
// 删除
await test.deleteMany({ "site": "example.com" });
// 查询
arr = await test.find().toArray();
console.log(arr);
} catch (err) {
console.log("错误:" + err.message);
} finally {
if (conn != null) conn.close();
}
}
dataOperate();原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。