如何从React.js中的用户ID获取用户名

我已经用猫鼬创建了这个模式

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:{}
};

元素问题存储问题对象,该对象包含提出问题的用户名,问题本身以及回答的人。

在.js文件中的某些位置,我可以获取通过简单回答的用户ID question.buzzed.map(user=> <h1> {user._id} </h1>), 但是如何获得该用户名,我也为用户提供了一个架构,该架构具有名称,id,...等属性

cimsimon 回答:如何从React.js中的用户ID获取用户名

您应该使用populate方法。类似于SQL中的join的猫鼬,因为它将您的答案连接到用户集合。根据您的代码,它看起来可能像这样:

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

或类似的内容:

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

有关更多信息,请阅读populate documentation

,

U可以使用$ lookup。

var aggregate = [
  {
    $unwind: "$answerd"
  },{
    $lookup: {
      from: "users",localField: "user",foreignField: "_id",as: "user"
    }
  }
];

Questions.aggregate(aggregate,function(err,users) {


})
本文链接:https://www.f2er.com/3163170.html

大家都在问