如何使用类型为String的自定义ObjectId填充



我有一个用于身份验证的firebase项目。我还将额外的用户信息保存在mongodb中,并将firebase用户的uid分配给用户模型的_id字段。为了做到这一点,我必须将ObjectId的类型设置为String,否则mongodb不允许我保存用户,因为firebase uid比ObjectId长一点。ObjectId的类型似乎是:String,我不能再在查询中使用populate。

以下是型号:

const UserSchema = new Schema({
_id: String,
name: String,
});
const SurveySchema = new Schema({
user_id: { type: String, ref: "users" },
category: String,
});

我试图设置user_id: { type: mongoose.ObjectId, ref: "users" },但我只是得到了一个错误(强制转换为ObjectId失败(,而不是未定义的。

这是我使用populate的控制器:

const SurveyList = await Survey.find(
{
user_id: req.currentUser.uid,
category: "example",
},
"_id user_id category createdAt updatedAt"
).populate("user_id");

我检查了一下,id匹配,但我仍然没有定义。当我有了常规的mongoObjectId时,填充就可以工作了,但在我开始使用firebase后,它就不再工作了。

我得到的回复是这样的:

"SurveyList": [
{
"status": "1",
"_id": "60abcd94e9cddb2ba44f24b4",
"user_id": null,
"category": "Health",
"createdAt": "2021-05-24T16:00:20.688Z",
"updatedAt": "2021-05-24T16:00:20.688Z"
}
]

请注意,错误是在我将_id更改为type:String之后才开始发生的。当它是默认的mongoose.ObjectId时,它曾经工作得很好

您无法填充用于存储对用户id的引用的字段。该字段将用于填充虚拟字段。如果你想做的是有一个虚拟字段SurveyList[i].user来检索每个SurveyList条目中的用户数据,你需要创建它:

SurveySchema.virtual("user", {
ref: "users",
localField: "user_id",
foreignField: "_id",
justOne: true,
});

然后,您需要填充虚拟字段:

const SurveyList = await Survey.find(
{
user_id: req.currentUser.uid,
category: "example",
},
"_id user_id user category createdAt updatedAt"
).populate("user");

最新更新