将 id(主键)发送到节点中的 2 个不同数据库(Mongo,Psql)

Sending id (primary key) to 2 different databases in Node (Mongo,Psql)

我有一个待办事项列表作业,我想用 2 个具有相同数据的不同数据库创建它。我怎样才能在 mongo 和 psql 中拥有相同的主键。我想在后端用 UUID 来做。有一种基本的方法吗?对不起,我是初学者。

这是我的 addToDo 的一个例子,我怎样才能拥有相同的 prim 密钥?

const addTodo = async (req, res, next) => {
  const { content } = req.body;

  const createdPlace = new Url({
    content: content,
    enable: false,
  });
  // Sending it To Mongo
  try {
    await createdPlace.save();
    await pool.query("INSERT INTO todo (content, enable) VALUES (, )", [
      content,
      false,
    ]);
  } catch (err) {
    const error = new HttpError("Creating Place fails mongo");
    return next(error);
  }

  res.sendStatus(200);
};

MongoDB 和 Postgres 默认处理主键的方式不同,但您可以使它们工作相同。

在MongoDB中,主键字段称为_id,它最常由客户端生成(但也可以由服务器生成),默认情况下是转换为特殊类型的十六进制字符串.

在 Postgres 中主键可以是任何字段,默认最常见的是 id,该值通常是一个自动递增的整数,由服务器生成。

均衡两个数据库:

  • 在客户端创建id值。您可以使用 MongoDB 驱动程序生成新的 ObjectId,将该值转换为字符串并将字符串值用于两个数据库。
  • 在 Postgres 中调用您的主键列 _id
  • 声明字符串类型的 Postgres 列。

简单而完美的答案。

const addTodo = async (req, res, next) => {
  const { content} = req.body;

  const createdPlace = new Url({
    content: content,
    enable: false,
  });
  // Sending it To Mongo
  try {
    console.log(createdPlace._id);
    await createdPlace.save();
    await pool.query(
      "INSERT INTO todo (todo_id ,content, enable) VALUES (, , )",
      [createdPlace._id, content, false]
    );
  } catch (err) {
    const error = new HttpError("Creating Place fails");
    return next(error);
  }

  res.sendStatus(200);
};