【问题标题】:How can I get a specific key value from another schema, By comparing if they have same key value?如何从另一个模式中获取特定的键值,通过比较它们是否具有相同的键值?
【发布时间】:2026-01-20 07:35:01
【问题描述】:

我有 Node.js 应用程序,由 express 提供服务,我有两个不同的猫鼬模式 userModel 和 postMode,我的前端是用 React.js 制作的。我正在创建一个将创建和显示帖子的组件。显示帖子将包含用户名、头像、日期、文本和图像。问题是头像在 userModel 中。有没有办法我也可以显示另一个模式的头像?我想我会根据它们是否具有相同的键值来比较这两个模式,因为它们都有用户名。为了显示帖子,我发送 Axios 以获取基于 postModel 的请求。

Backend
export const getUserRelatedPost = asyncHandler(async (req, res) => {
  const postData = await postModel.find({});
  res.json(postData);
});

架构 后模型

用户模型

谢谢!

【问题讨论】:

  • 我不完全确定我理解您的要求,但在查看您共享的两个架构时,用户名元素中的值不匹配。
  • 我认为更好的方法是在您的帖子中嵌入用户数据或创建一个引用(然后填充)到 UserModel。当您创建新帖子时,您可以限制您提出的请求数量。
  • @ScottGnile 我很抱歉,但这两个用户名都应该是 johndoe。我想要的输出是我想从 userModel 获取头像值,以便我可以在我的帖子组件上使用它,但问题是 postModel 是我在帖子组件上使用的那个。
  • @VoQuocThang 先生,你能给我一些关于如何做到这一点的链接吗?谢谢!
  • @rjc30 这里是填充方法:*.com/questions/38051977/…

标签: node.js reactjs mongodb mongoose


【解决方案1】:

你可以使用猫鼬的填充功能

https://mongoosejs.com/docs/populate.html

在您的 postModel 中添加一个虚拟“用户”元素

const postSchema = Schema({
    //your existing postModel definition

});

postSchema.virtual('user', {
    ref: 'User',
    localField: 'username',
    foreignField: 'username',
    justOne: true
});

我假设您的 userModel 导出用户是这样的:

const userSchema = Schema({
    //your existing userModel definition
})

const User = model('User', userSchema);

那么在你的快递路线中,你应该能够做这样的事情:

export const getUserRelatedPost = asyncHandler(async (req, res) => {
    const postData = await postModel.find({})
        .populate({
            path: 'user',
            select: 'avatarPhoto'
        });
    //you should be able to access the avatar photo(s) like this
    console.log(postData.map(u => u.user.avatarPhoto)

    res.json(postData);
});

【讨论】:

  • 这假设两个模型中用户名中的值是相同的
  • 感谢您的帮助!
  • 如果我使用 .find 会出现问题,avatarPhoto 未定义,但如果我使用 .findOne,它会起作用。
  • 没错,find 返回的是一个数组,而不是一条记录……我的错。
  • 是的,我仍在寻找解决此问题的方法。感谢您的帮助!
最近更新 更多