如何将数据库表引用到mongoDB中的另一个数据库表,就像我有2个数据库
- 根数据库包含
user
表 - 公司数据库包含
companies
表
现在我想引用companies
表到user
表。是否有任何可能的方法来连接这在nodejs和mongodb
您可以这样做来在mongoose中跨数据库填充:
import mongoose, { Schema, Types } from "mongoose"
const db1 = mongoose.createConnection('mongodb://127.0.0.1:27017/company');
const db2 = mongoose.createConnection('mongodb://127.0.0.1:27017/root');
const companySchema = new Schema({ name: String });
const Company = db1.model('Company', companySchema);
const userSchema = new Schema({
name: String,
company: {
type: Types.ObjectId,
ref: Company
}
})
const User = db2.model('User', userSchema);
const users = await User.find().populate("company")
console.log(users)
db1.close()
db2.close()
结果:
[
{
_id: new ObjectId("642d5cf980d1e56765814094"),
name: 'myUser',
company: {
_id: new ObjectId("642d5cb580d1e56765814093"),
name: 'myCompany'
}
}
]
从mongosh:
company> db.companies.find()
[ { _id: ObjectId("642d5cb580d1e56765814093"), name: 'myCompany' } ]
company> use root
switched to db root
root> db.users.find()
[
{
_id: ObjectId("642d5cf980d1e56765814094"),
name: 'myUser',
company: ObjectId("642d5cb580d1e56765814093")
}
]