首页 > 解决方案 > 猫鼬居住

问题描述

我是 mongoose 和 mongodb 的新手,我一直在尝试将我的用户与一堆图片帖子联系起来。我读了很多关于 mongoose populate 的文章,但我不断收到空图像 []。

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    email: {
        type: String,
        required: true
    },
    username: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    images: [
        {
            type: mongoose.Schema.Types.ObjectId, 
            ref: 'Image'
        }
    ]
});

module.exports = mongoose.model('User', userSchema);

const mongoose = require('mongoose');

const imageSchema = new mongoose.Schema({
    id: mongoose.Schema.Types.ObjectId,
    image: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
})

module.exports = mongoose.model('Image', imageSchema);

const getOne = async (userId) => {

    let lastTenImages = await User.findById(userId).populate('images').lean();

     console.log(lastTenImages.images);

    // return lastTenImages
}

我还使用了 mongoose.Types.ObjectId 而不是 Schema 但仍然得到相同的结果 - 一个空数组

标签: javascriptnode.jsmongoose

解决方案


在我看来,您应该丢弃不能作为用户模型链接的 id 部分。换句话说,尝试类似:

const imageSchema = new mongoose.Schema({
image: {
    type: String,
    required: true
},
description: {
    type: String,
    required: true
},
})

我认为这应该填充正确的数组。

此外,当您获得值时,您将获得一个对象数组。所以你需要映射它。lastTenImages.images不会产生任何东西。


推荐阅读