首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >未填充Mongoose“populate()”

未填充Mongoose“populate()”
EN

Stack Overflow用户
提问于 2020-07-30 01:13:06
回答 2查看 57关注 0票数 1

因此,我正在使用MEARN堆栈构建一个简单的应用程序。

问题是,我希望获得用户的信息(姓名、电子邮件等)。要放在产品的'user‘属性,但它不工作(Postman request return 500 status Server error),我不知道我做错了什么,提前谢谢!我的代码片段:

我的用户模型:

代码语言:javascript
复制
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)

我的产品型号:

代码语言:javascript
复制
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)

我的请求是:

代码语言:javascript
复制
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')
     } 
 })
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-07-30 01:38:19

您的ref值需要与模型user引用的名称相匹配。因此,您需要将其更改为:

代码语言:javascript
复制
user:{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'user'
},
票数 2
EN

Stack Overflow用户

发布于 2020-07-30 01:26:49

您必须指定路径:populate({path:'user'}) Try:

代码语言:javascript
复制
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')
     } 
 })
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63158961

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档