nodeJS 使用 mongodb save数据

源代码请查看GitHub:
https://github.com/slhuang520/study/tree/master/web/nodeJS/mongoDB/save.js

save() 方法将在后面的版本中被抛弃。

目前使用的 mongodb nodeJS driver 版本为 3.2.3

const MongodbClient = require("mongodb").MongoClient,
    assert = require("assert");
// save deprecated
(async function () {
    const url = "mongodb://127.0.0.1:27017",
        dbName = "mydb",
        client = new MongodbClient(url);

    try {
        await client.connect();
        const db = client.db(dbName);

        let col = await db.collection("user");
        col.save({name: "Kin", age: 40}, function (err, res) {
            console.log(res.ops); //添加的记录
            console.log(res.result); //执行的结果集
            assert.equal(null, err);
            assert.equal(1, res.result.n);
            assert.equal(1, res.result.ok);
            assert.equal("Kin", res.ops[0].name);
            assert.equal(40, res.ops[0].age);
        });

    } catch (e) {
        console.log(e.stack);
    } finally {
        client.close();
    }
})();
/*
[ { name: 'Kin', age: 40, _id: 5cd1a3134d2fb23b94c3ca3d } ]
{ n: 1, ok: 1 }
*/

你可能感兴趣的:(mongodb,javascript)