【问题标题】:Ref in mongoose model not giving output猫鼬模型中的参考未提供输出
【发布时间】:2022-12-10 00:56:31
【问题描述】:

我正在使用 mongoose 来定义模式。我有两个模式用户和用户详细信息。我想要 userdetail 中的用户数据

我有以下架构,但我没有得到输出。我认为代码是正确的,但不明白为什么没有输出……相反,我得到的是空数组。

const mongoose = require("猫鼬")

const UserDetailSchema = mongoose.Schema({
    电话 : {
        类型:数字
    },
    名 : {
        类型:字符串
    },
    姓 : {
        类型:字符串
    },
    产品图片:{
        数据:缓冲区,
        内容类型:字符串
    },
    已删除:{
        类型:布尔值,
        默认值:假
    },
    用户身份 : {
        类型:字符串,
    },
    数据 : [{
        类型:mongoose.Schema.Types.ObjectId,
        参考:“用户”
    }],
},
{时间戳:真})

const UserDetail = new mongoose.model("userdetail",UserDetailSchema);

module.exports = UserDetail;

我的用户模式是

const mongoose = require("猫鼬");

    const UserSchema = mongoose.Schema({
      电子邮件: {
        类型:字符串,
        要求:真实
      },
      密码: {
        类型:字符串,
        要求:真实
      },
      已删除:{
        类型:布尔值
      },
    },
    {时间戳:真});

    module.exports = mongoose.model("user", UserSchema);

查询是,

<pre>

router.get("/UserDetail",async (req,res)=>{
    try{
        const UsersData= await UserDetail.find();
        res.json(UsersData)
    }catch(e){
        res.status(500).json({ message: e.message })
    }
})

</pre>

即使我只使用查找,我也必须只使用 id 获取数据吗?

输出是 -

任何帮助,将不胜感激

router.patch("/UserDetail/:id",Auth,upload.single("productimage"),async(req,res)=>{

    尝试{


        const id = req.params.id;

        const updatedData = req.body;

        updatedData.productimage = {data: fs.readFileSync('upload/' + req.file.filename),
        contentType: 'image/png'};
        const options = { new: true };


        const result = await UserDetail.findOneAndUpdate(
            id、更新数据、选项
        )

        重新发送(结果)
    }抓住(e){
        res.status(500).json({ message: e.message })
    }
})

【问题讨论】:

  • 你能分享你正在写的查询吗?
  • 当然哈立德......我已经更新了问题......
  • 发布存储在数据库中的数据。数据库中存储的数组中是否有任何 id?
  • 嗨 Marc,db 中没有数组,这个方括号在那里是因为我在模型中给出了它(请参考我在 userdetail 模式中放入数组的数据值)....如果我不给出方括号,它什么都不显示

标签: node.js mongoose backend mern


【解决方案1】:

您可以使用 populate 函数填充字段:

const userDetails = await UserDetail.find({}).populate('data').exec();

【讨论】:

  • 它仍然没有给出输出 lpizzinidev....
  • @NakeebRaut 您可以在添加新的UserDetail 实例的地方发布代码吗?
  • 实际上代码很长,其中包含可能相互关联的不同操作......所以它可能会令人困惑......我希望你理解我的担忧
  • populate 查询应该填充引用,所以问题可能在于您将 data 插入 UserDetail 集合的方式
  • 非常感谢...我也会朝那个方向检查代码
【解决方案2】:

首先,您需要对 userDetail 架构中的 userID 进行一些更改。请将其发送至UserID:{type : mongoose.Schema.Types.ObjectId},,因为它将在以后的聚合过程中为您提供帮助,您还可以从 userDetail 模型中删除数据,因为在您保存数据之前它不会存储任何数据.最后尝试运行这个聚合查询。

 const UsersData= await UserDetails.aggregate([
    {$lookup:
     {
     from: "users",
     localField: "userID",
     foreignField: "_id",
     as: "data" 
     }
    }])

这样,您各自的用户详细信息将显示在数据数组中。

【讨论】:

    【解决方案3】:

    在您的模型中进行更改,然后填充数据。

    const mongoose = require("mongoose")
    
    const UserDetailSchema = mongoose.Schema({
    Phone : {
        type : Number
    },
    FirstName : {
        type : String
    },
    LastName : {
        type : String
    },
    productimage : {
        data : Buffer,
        contentType : String
    },
    IsDeleted:{
        type:Boolean,
        default:false
    },
    UserID : {
        type : String,
    },
    data : {
        type: mongoose.Schema.Types.ObjectId,
        ref: "user"
    },
    },
    {timestamps: true})
    }
    

    填充查询

    let Model=//import your model here
    let userdata=await Model.find().populate("data")
    console.log(userdata)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-14
      • 2013-01-25
      • 2015-03-16
      • 2015-07-06
      • 2020-04-07
      • 2015-01-13
      • 2017-09-13
      • 2015-11-29
      相关资源
      最近更新 更多