菜鸟求教一个 Nodejs 关于id自增的问题

菜鸟求教一个 Nodejs 关于id自增的问题

function Ids(tablename, id) { this.id = id; this.tablename = tablename; //tablename为id1,id2,id3 } module.exports = Ids; Ids.getId = function (tablename, callback) { mongodb.open(function (err, db) { db.collection(‘ids’, function (err, collection) { collection.findAndModify({“tablename”:tablename}, [], {$inc:{‘id’:1}}, {new:true, upsert:true}, function (err, doc) { mongodb.close(); callback(doc.id); }); }); }); } 这段代码中,如果表中共存入三个id值,tablename分别为id1,id2,id3,可以通过getId(id1);getId(id2);getId(id3);这样的方法取得id的值吗


2 回复

要解决Node.js中的ID自增问题,我们需要确保每个tablename都有独立的计数器,并且每次调用getId函数时,都能正确地递增对应的计数器。下面是一个改进后的代码示例,它使用MongoDB来存储每个tablename的当前ID值。

改进后的代码

const mongodb = require('mongodb'); // 假设你已经安装了mongodb模块
const MongoClient = mongodb.MongoClient;

function Ids(tablename, id) {
    this.id = id;
    this.tablename = tablename;
}

module.exports = Ids;

Ids.prototype.getId = async function (tablename) {
    const url = 'mongodb://localhost:27017'; // MongoDB连接URL
    const dbName = 'yourDatabaseName'; // 数据库名称

    let client;
    try {
        client = await MongoClient.connect(url);
        console.log("Connected correctly to server");
        const db = client.db(dbName);

        const collection = db.collection('ids');
        
        const result = await collection.findOneAndUpdate(
            { "tablename": tablename },
            { $inc: { "id": 1 } },
            { returnDocument: 'after', upsert: true }
        );

        return result.value.id;
    } catch (err) {
        console.error(err.stack);
    } finally {
        if (client) {
            client.close();
        }
    }
};

// 使用示例
(async () => {
    const IdsInstance = new Ids();
    const id1 = await IdsInstance.getId('id1');
    console.log(`ID for id1 is ${id1}`);

    const id2 = await IdsInstance.getId('id2');
    console.log(`ID for id2 is ${id2}`);

    const id3 = await IdsInstance.getId('id3');
    console.log(`ID for id3 is ${id3}`);
})();

解释

  1. 初始化:

    • Ids构造函数接收tablename和初始id作为参数。
  2. getId方法:

    • 使用findOneAndUpdate方法来查找并更新指定tablename的文档。
    • 如果文档不存在,则通过upsert: true创建一个新的文档。
    • 使用$inc操作符将id字段加1。
    • 返回更新后的id值。
  3. 异步处理:

    • 由于数据库操作是异步的,我们使用async/await语法来简化异步代码的编写和阅读。
  4. 示例用法:

    • 创建Ids实例,并调用getId方法获取不同tablename对应的ID值。

这样,每次调用getId方法时,都会返回一个递增的ID值,同时保证每个tablename的ID都是独立递增的。


你提供的代码有一些问题需要修正,包括变量名、字符串引号类型以及回调函数中的返回值。下面是修正后的代码示例,并解释了如何实现ID自增功能。

修正后的代码

const mongodb = require('mongodb'); // 假设你使用的是mongodb库
const MongoClient = mongodb.MongoClient;

function Ids(tablename, id) {
    this.id = id;
    this.tablename = tablename;
}

Ids.prototype.getId = async function (tablename) {
    const url = 'mongodb://localhost:27017/yourDatabaseName';
    const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });

    try {
        await client.connect();
        const db = client.db();
        const collection = db.collection('ids');

        const result = await collection.findOneAndUpdate(
            { tablename },
            { $inc: { id: 1 } },
            { returnDocument: 'after', upsert: true }
        );

        return result.value.id;
    } catch (error) {
        console.error("Error occurred:", error);
        throw error;
    } finally {
        client.close();
    }
};

module.exports = Ids;

解释

  1. 函数定义Ids构造函数用于存储表名和初始ID。
  2. 异步方法getId方法被定义为async,这样可以更方便地处理异步操作(如数据库查询)。
  3. MongoDB连接:使用MongoClient连接到MongoDB服务器,并确保使用了正确的URL。
  4. 查询和更新:使用findOneAndUpdate方法查找并更新指定表的ID。$inc操作符用于增加ID的值,upsert: true确保如果没有找到匹配的文档,则插入一个新的文档。
  5. 错误处理:使用try...catch语句捕获并处理可能出现的错误。
  6. 关闭连接:在操作完成后关闭数据库连接。

通过这种方式,你可以调用getId('id1')getId('id2')getId('id3')来分别获取每个表的下一个ID值。

回到顶部