【问题标题】:How do i use populate with a custom ObjectId of a type: String?如何使用类型为自定义 ObjectId 的填充:字符串?
【发布时间】:2021-05-25 18:03:55
【问题描述】:

我有一个用于身份验证的 firebase 项目。我还将其他用户信息保存在 mongodb 中,并将 firebase 用户的 uid 分配给用户模型的 _id 字段。为此,我必须将 ObjectId 的类型设置为 String,否则 mongodb 不会让我保存用户,因为 firebase uid 比 ObjectId 长一点。似乎 ObjectId 的类型是:String,我不能再在我的查询中使用填充。

以下是模型:

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" },但我只是得到一个错误(Cast to ObjectId failed)而不是未定义。

这是我使用填充的控制器:

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

我检查了,ID 匹配,但我仍然不确定。当我有常规的 mongo ObjectIds 时,填充曾经可以工作,但在我开始使用 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时,它曾经工作正常@

【问题讨论】:

  • 为什么不尝试通过指定路径来填充?是用户是你的型号名称?如果是这样,那么尝试这样.populate({ path : 'user_id', model: 'users'})
  • @xetryDcoder 不幸的是这不起作用,仍然得到"user_id":null
  • 您是否能够在不填充 SurveyList 的情况下获取数据?
  • 是的,我得到了所有的数据,但是我想要填充的字段只是 null
  • 你能用你得到的回复更新问题吗?

标签: javascript node.js mongodb firebase mongoose


【解决方案1】:

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

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");

【讨论】:

  • 感觉我快接近了,这种方法使用 id 本身填充字段,如下所示:"user_id":"kgnNFAbQZkOQu7QAz0qxybo3Yc22"。知道如何填充所有值?
  • 我认为字段 user_id 不需要以任何方式填充:它是 user._id,正如您在创建新的 SurveyList 条目时介绍的那样。您检查过 SurveyList[0].user 吗?如果 .populate("user") 正常工作,则 SurveyList 数组中的每个项目都应该有一个 .user 字段,其中包含所有用户的原始信息。
  • 不,.user 字段不存在。以前我使用了populate("user_id") 方法,它返回了.user_id 中的用户对象。在我不得不将用户模型的 _id 字段更改为 type: String 之前,它运行良好
猜你喜欢
  • 2019-06-28
  • 2017-11-05
  • 2021-04-17
  • 2020-03-17
  • 2014-07-27
  • 1970-01-01
  • 2011-05-03
  • 2015-11-04
  • 1970-01-01
相关资源
最近更新 更多