mongodb 与 postgres SQL"/>
连接 mongodb 与 postgres SQL
我在 mongodb 中有一个 post 模式。例子:
const Post = new Schema(
{
user_id: {
type: Number,
required: true,
},
title: {
type: String,
required: true,
},
description: {
type: String,
},
attached_files: [IdeaMedia],
status: {
type: Number,
default: 1,
enum: Object.values(IdeaStatus), // 0- inactive, 1- active, 2- delete
},
},
{
timestamps: { createdAt: "created_at", updatedAt: "updated_at" },
}
);
我在 postgres sql 中有一个用户表。示例:(我正在使用 sequelize ORM)
const UserSchema = sequelize.db.define(
"user",
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
first_name: {
type: Sequelize.STRING,
allowNull: true,
},
last_name: {
type: Sequelize.STRING,
allowNull: true,
},
avatar: {
type: STRING,
allowNull: true,
},
phone: BIGINT,
email: {
type: STRING,
allowNull: false,
unique: true,
set(value) {
this.setDataValue("email", value.trim().toLowerCase());
},
},
status: {
type: INTEGER,
defaultValue: 1,
validate: {
isIn: {
args: [[0, 1, 2]],
msg: "Invalid Status Value",
},
},
},
},
{
tableName: "user",
createdAt: "created_at",
updatedAt: "updated_at",
}
);
现在我想获取帖子列表(来自不同用户的帖子)。有什么方法可以连接两个数据库吗?
我知道我可以在 Post 模式中存储更多的 user_id,比如 first_name、last_name、avatar,但是如果用户更新了他们的头像或 first_name,那么我将不得不更新属于该用户的所有帖子。这是不可行的。那么,有什么办法可以连接这两个表吗?或者我应该尝试另一种方法吗?
我也知道我可以使用单个数据库 postgres 或 mongodb 来存储用户和帖子,但我想知道这是否可行。
谢谢你的帮助。
回答如下:使用两个数据库并不少见,但是将它们用于相互交叉的关系数据是不明智的。
但首先,回答你的问题:
- 从 MongoDB 获取完整的帖子列表
- 使用
创建第二个列表,将Array.map()
的所有唯一值放在一起user_id
- 使用 ID 数组从 Postgres 获取用户数据 ^
- 适当组合所有结果
有点例子(非常伪,当然根据你的项目进行调整)
// array of Post objects
const posts = getPostsFromMongo();
const userIds = posts.map(post => {
return post.user_id;
});
// use Set() to only return unique IDs
const userIdSet = new Set(userIds);
// array of User objects
const users = getUsersFromPostgres(userIdSet);
几种不同的组合方式,这里有两种选择:
User
对象添加为新的userInfo
属性
User
userInfo
const combined = posts.map(post => {
post.userInfo = users.find(user => {
return user.id === post.user_id;
});
return post;
});
User
对象数据分布在与 Post
相同的级别(前缀为“user_”,因为某些字段冲突
User
Post
const combined = posts.map(post => {
const userInfo = users.find(user => {
return user.id === post.user_id;
});
return {
...post,
user_first_name: userInfo.first_name,
user_last_name: userInfo.last_name,
user_avatar: userInfo.avatar,
user_status: userInfo.status,
// ... rest of userInfo, except "id" since it already exists as Post.user_id (and assuming Post.id exists, would also conflict with that)
};
});
我还是推荐反对这个DB安排
最直接的原因是您的两个数据库不会在彼此之间提供参照完整性(因此 Mongo 中的
user_id
可能指向 Postgres 中不再存在的行)。如果您想同时使用它们,请将其中一个(推荐 Postgres)设为主数据库并使用逻辑复制将所有更新实时流式传输到辅助数据库。
第二个原因是拥有单一的事实来源(您目前可能没有没有这样做,但看起来不太可能)。一旦两个数据库具有相同的数据(来自复制),您在读取数据时只能从一个(Mongo)访问。
在实践中如何完成这样的事情的一个很好的例子是Debezium
更多推荐
连接 mongodb 与 postgres SQL
发布评论