【问题标题】:How to get user name from user id in React.js如何从 React.js 中的用户 id 获取用户名
【发布时间】:2020-03-01 07:13:31
【问题描述】:

我用猫鼬创建了这个架构

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const QuestionSchema = new mongoose.Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'users'
    },
    question:{
        type:String
    },
    name:{
        type:String,
    },
    answerd:[
        {
            user:{
                type:mongoose.Schema.Types.ObjectId,
                ref:'users'
            }
        }
    ]
})

module.exports = Question = mongoose.model('question',QuestionSchema);

在我的全局状态 (REDUX) 我有状态

const initialState = {
    questions:[],
    question:null,
    loading:true,
    error:{}
};

元素 questions 存储问题对象,其中包含提出问题的用户的姓名、问题本身以及已回答的人。

在 .js 文件中的某些地方,我可以通过简单的方式获取已回答的用户的 ID question.buzzed.map(user=> <h1> {user._id} </h1>), 但是如何获得这个用户名,我也有一个用户模式,它具有名称、id、...等属性

【问题讨论】:

    标签: node.js reactjs mongodb mongoose redux


    【解决方案1】:

    你可以使用 $lookup。

    var aggregate = [
      {
        $unwind: "$answerd"
      },
      {
        $lookup: {
          from: "users",
          localField: "user",
          foreignField: "_id",
          as: "user"
        }
      }
    ];
    
    Questions.aggregate(aggregate, function(err, users) {
    
    
    })
    

    【讨论】:

      【解决方案2】:

      您应该使用populate 方法。就像 mongoose 的 SQL 中的 join 一样,因为它将您的答案连接到用户集合。根据您的代码,它可能如下所示:

      Question.find({}).populate("answerd")
      

      或类似的东西:

      Question.find().populate({ path: 'answerd', select: 'username' });
      

      更多信息请阅读populate documentation

      【讨论】:

        猜你喜欢
        • 2021-05-07
        • 2014-12-18
        • 1970-01-01
        • 2019-05-03
        • 1970-01-01
        • 2023-04-11
        • 2016-04-27
        • 2019-12-30
        • 2021-07-18
        相关资源
        最近更新 更多