【问题标题】:Call a related collection via populate通过填充调用相关集合
【发布时间】:2018-06-30 11:16:15
【问题描述】:

我尝试通过Mongoose populate.调用某个用户的相关日志列表谁可以帮助我完成响应?

这些是方案:

const logSchema = new Schema({
    logTitle: String,
    createdOn:
    { type: Date, 'default': Date.now },
    postedBy: {
        type: mongoose.Schema.Types.ObjectId, ref: 'User'}
   });

const userSchema = new Schema({
    
    firstName: {
        type: String,
        required: true
    },
    lastName: {
        type: String,
        required: true
    }
    logs: { type: mongoose.Schema.Types.ObjectId, ref: 'logs' }
     
});

mongoose.model('User', userSchema);
mongoose.model('logs', logSchema);
受到猫鼬纪录片(见上文)和其他与此主题相关的questions 的启发,我认为我在取得好成绩方面取得了很大进展。请求该用户。我怀念将其“翻译”为 Express 的体验。

const userReadLogs = function (req, res) {
    if (req.params && req.params.userid) {
        User1
            .findById(req.params.userid)
            .populate('logs') 
            .exec((err, user) => {
                if (!user) { }); // shortened
                    return;
                } else if (err) {
                    return; // shortened
                }

                response = {  //question
                    log: {  
                        user: user.logs 
                    }
                };

             res   
                    .status(200)
                    .json(response);
            });
    } else { }); // 

    }
};

Postman 等中的响应是这样的:

{
    "log": {5a57b2e6f633ce1148350e29: logTitle1,
    
            6a57b2e6f633ce1148350e32: newsPaper44,
            
            51757b2e6f633ce1148350e29: logTitle3
    
}

【问题讨论】:

  • 您也可以发布一些示例文档吗?虽然这是一个糟糕的设计,但您在用户文档中保存了日志的引用 (_id),并在日志中保存了用户的引用 (_id),您应该只在 logSchema 中保存它并相应地引用它LogsModel.find({ ...query }).populate('postedBy').then( ...callback )
  • 我认为在 Schema 中使用 Mongoose Populate (mongoosejs.com/docs/populate.html) 的示例做得很好,而不是“作家”和“故事”,我使用了“用户”和“日志” '。我认为它的工作方式相同?响应(示例文档)将是 JSON 格式的特定用户 ID 的 logTitles 列表。
  • 你能告诉我们具体是什么问题吗,你的问题很模糊。
  • 在我的函数 userReadLogs 中有一个'response = ..'。我需要添加什么代码来获得我的 .json 结果?提前致谢
  • 你现在得到什么回应?

标签: node.js express mongoose


【解决方案1】:

首先,logs 不会是日志列表;它将是object。如果您希望每个用户有多个日志,则需要将其存储为array:logs: [{ type: mongoose.Schema.Types.ObjectId, ref: 'logs' }]

来自Mongoose 文档:“填充的路径不再设置为其原始 _id ,它们的值被替换为从数据库返回的猫鼬文档,方法是在返回结果之前执行单独的查询。" 换句话说,您的query user.logs 将是每个用户的logs document。它将包含所有properties,在您的情况下为logTitlecreatedOnpostedBy

从服务器发送user.logsjson 就像:res.json(user.logs) 一样简单。所以您的查询可能如下所示:

const userReadLogs = function (req, res) {
    if (req.params && req.params.userid) {
        User1
            .findById(req.params.userid)
            .populate('logs') 
            .exec((err, user) => {
                if (!user) { }); // shortened
                    return;
                } else if (err) {
                    return; // shortened
                }
                res.status(200).json(user.logs)
            });
    } else { }); // 

    }
};

我希望这能让它更清楚一点!

【讨论】:

  • 太棒了!如果您发现它有用,请考虑将答案标记为正确或投票,以帮助可能遇到类似问题的其他社区成员。您可以阅读更多关于接受和支持答案here
猜你喜欢
  • 2011-03-18
  • 2021-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-26
  • 2022-01-15
  • 2010-11-27
相关资源
最近更新 更多