【问题标题】:Cannot populate fields in express and Mongodb无法在 express 和 Mongodb 中填充字段
【发布时间】:2020-11-29 14:04:08
【问题描述】:

我有两个模型 Post 和 Users,我想填充帖子字段

const PostSchema = new Schema({
    text: { 
        type: String 
    },
    author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'user'
    }
})
const UserSchema = new Schema({
    username: {
        type: String, 
    }
})
router.post('/', async (req,res) => {
    try {
        let joe = new User({username: "joe"})
        await joe.save()
        
        let postText = {text: "my name is joe", author: joe._id}
        let postByJoe = new Post(postText)
        await postByJoe.save()

        let users = User.find().populate('author') 
        res.json({users})
    } catch (error) {
        console.log(error.message)
        res.json(error.message)
    }
    
})

问题是我得到一个错误,我不知道该怎么做。我完全不确定问题是什么。任何帮助将不胜感激

"将循环结构转换为 JSON\n --> 从具有构造函数 'NativeTopology' 的对象开始\n | 属性 's' -> 具有构造函数 'Object' 的对象\n | 属性 'sessionPool' -> 具有构造函数的对象' ServerSessionPool'\n --- 属性 'topology' 闭环"

【问题讨论】:

    标签: javascript mongodb express mongoose


    【解决方案1】:

    架构中的内容不同,您只能在架构中填充 Schema.Types.ObjectId 字段。似乎您正在尝试填充 Post 模型的作者字段。

    将这行let users = User.find().populate('author') 替换为let users = Post.find().populate('user') Your code should be like the one below:

    router.post('/', async (req,res) => {
    try {
        let joe = new User({username: "joe"})
        await joe.save()
        
        let postText = {text: "my name is joe", author: joe._id}
        let postByJoe = new Post(postText)
        await postByJoe.save()
    
       let data = await Post.find().populate('user') 
        // map through the object returned
        const users = data.map((user) => user)
        res.json({users})
    } catch (error) {
        console.log(error.message)
        res.json(error.message)
    }
    
    })
    

    阅读更多关于猫鼬种群的信息here

    【讨论】:

    • 一个大问题是我也没有使用等待。我已经更改了架构并使用了用户而不是作者,但我仍然有错误。然后我使用 await 并且错误消失了。非常感谢你
    猜你喜欢
    • 1970-01-01
    • 2021-04-19
    • 2021-07-09
    • 2013-11-03
    • 2021-12-13
    • 2021-02-16
    • 2015-05-03
    • 1970-01-01
    • 2019-10-19
    相关资源
    最近更新 更多