【问题标题】:Fetch user details based on userId which is referenced field in userDetails table根据 userDetails 表中引用的字段 userId 获取用户详细信息
【发布时间】:2018-02-02 04:33:59
【问题描述】:

数据库:MongoDB
后端:Node.js

数据库中有两个表:User 和 userDetails。 User 表中的 ObjectId 已在 userDetails 表中用作 userId 的引用。现在基于这个 userId 我想显示 userDetails。

我尝试创建一个函数并尝试在邮递员中对其进行测试,但我得到了空数据。当我在 api 测试工具 postman 中测试这个功能时,我没有得到任何用户详细信息。我无法理解为什么我没有得到任何数据。

函数如下:

  function getUserDetailByUserId(req, res) {
    userDetails.find(req.params.userId, (error, detail) => {
        if (error)
            res.send(error);
        res.json(detail);
    }).populate(userId);
} 

【问题讨论】:

标签: mongodb


【解决方案1】:

使用 ObjectId

新的 mongoose.mongo.ObjectID(req.params.userId)

function getUserDetailByUserId(req, res) {

    userDetails.findOne({userId: new mongoose.mongo.ObjectID(req.params.userId)})
    .populate(userId)
    .exec(function(error, detail){
        if (error)res.send(error);
        res.json(detail);
    });

} 

userDetail 架构:

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

const userDetailSchema = new Schema({
  dateOfBirth: {
    type: Date,
    required: true
  },
  gender: {
    type: String,
    required: true
  },
  country: {
    type: String,
    required: true
  },
  interest: {
    type: String,
    required: true
  },
  remarks: {
    type: String,
  },
  userId: {
    type: Schema.Types.ObjectId,  // Referencing the Registered Users in User Model by their ObjectId reference.
    ref: 'User'           // Creating a relation between User and UserDetails Model through unique ObjectId.
  }
});

module.exports = mongoose.model('UserDetails', userDetailSchema);

【讨论】:

  • 我还是没有得到数据
  • 还是没有得到
  • 请提供您的用户详细模型架构
  • 使用 global.userDetails =require('userDetail .. schma path here');在你的 app.js
  • 您的模型不需要正确,因此您无法访问您的 userDetails 架构
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-30
  • 1970-01-01
  • 2021-06-11
相关资源
最近更新 更多