Mongoose对象ID作为一个值



在MongoDB记录中,我有一个ObjectID。示例:

Record A
{
_id: ObjectId("62ecef6f8c1fa743580e9828"),
name: "John"
}
Record B
{
_id: ObjectId("62e14880ad84f0acd54ae930"),
title: "How to...",
user: ObjectId("62ecef6f8c1fa743580e9828"),
}

现在,正如您在记录B中看到的,它在用户中具有记录A的对象ID。有没有一种方法可以直接从记录B中获取用户对象,因为它有用户对象ID,或者我必须根据ID找到它?

这是可能的,有几种方法可以做到。

填充方法

首先,你需要在你的模型中添加参考:

const RecordA = new mongoose.Schema(
{
name: {
type: String
}
}
)
const RecordB = new mongoose.Schema(
{
title: {
type: String,
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: RecordA,
required: true,
}
}
)

然后,您可以通过添加.populate()方法来填充此字段。

RecordsA.find().populate('user')

点击此处阅读更多:Mongoose文档

$lookup聚合

您可以使用$lookup聚合:

RecordB.aggregate([
{ $lookup:
{
from: "RecordA",
localField: "user",
foreignField: "_id",
as: "user"
}
}
])

点击此处阅读更多:MongoDB文档

最新更新