【问题标题】:Mongoose 'populate()' not populating猫鼬'populate()'没有填充
【发布时间】:2020-11-19 08:38:29
【问题描述】:

所以我用 MEARN 堆栈构建了一个简单的应用程序。

问题是我想将用户信息(姓名、电子邮件等)放在产品的“用户”属性中,但它不起作用(邮递员请求返回 500 状态服务器错误) ,我不知道我在做什么错,提前谢谢!我的代码 sn-ps:

我的用户模型:

const mongoose = require('mongoose')

const UserSchema = mongoose.Schema({

    name : {
        type: String,
        required: true
    },
    email : {
        type: String,
        required: true,
        unique: true
    },
    password : {
        type: String,
        required: true
    },
    date : {
        type: Date,
        default: Date.now
    },
})

module.exports = mongoose.model('user',UserSchema)

我的产品型号:

const mongoose = require('mongoose')

const ProductSchema = mongoose.Schema({

    user:{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'users'
    },
    name : {
        type: String,
        required: true
    },
    description : {
        type: String,
        required: true
    },
    quantity : {
        type: Number,
        required: true
    },
    price : {
        type: Number,
        required: true
    },
    date : {
        type: Date,
        default: Date.now
    },
})

module.exports = mongoose.model('product',ProductSchema)

还有我的要求:

router.get('/:id', async (req,res) => {
     try {
          const product = await Product.findById(req.params.id).populate('user')
          res.json(product)
     } catch (err) {
          res.status(500).send('Server Error')
     } 
 })

【问题讨论】:

  • err 值应该告诉您问题出在哪里,但我猜您在ref 中使用了错误的型号名称。应该是ref: 'user'
  • @JohnnyHK 非常感谢!这就是问题的根源。 :)

标签: mongodb express mongoose mongoose-populate


【解决方案1】:

您的ref 值需要与模型名称user 引用相匹配。所以你需要把它改成:

user:{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'user'
},

【讨论】:

    【解决方案2】:

    你要指定路径:populate({path:'user'})试试:

    router.get('/:id', async (req,res) => {
         try {
              const product = await Product.findById(req.params.id).populate({path:'user'})
              res.json(product)
         } catch (err) {
              res.status(500).send('Server Error')
         } 
     })
    

    【讨论】:

    • 服务器错误,来自trycatch中的catch bloc
    猜你喜欢
    • 2020-07-25
    • 1970-01-01
    • 2016-02-14
    • 2015-07-13
    • 2016-10-10
    • 2019-09-16
    • 2021-10-07
    • 2015-07-13
    相关资源
    最近更新 更多