首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mongoose种群

Mongoose种群
EN

Stack Overflow用户
提问于 2021-04-09 07:15:28
回答 1查看 37关注 0票数 0

我是mongoose和mongodb的新手,一直在尝试用一堆图片帖子来连接我的用户。我读了很多关于mongoose populate的文章,但我总是得到一些空图像[]。

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

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

代码语言:javascript
复制
const getOne = async (userId) => {

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

     console.log(lastTenImages.images);

    // return lastTenImages
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-30 02:28:30

在我看来,您应该丢弃id部分,它不能作为到用户模型的链接。换句话说,试着这样做:

代码语言:javascript
复制
const imageSchema = new mongoose.Schema({
image: {
    type: String,
    required: true
},
description: {
    type: String,
    required: true
},
})

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

此外,当您获得值时,您将获得一个对象数组。因此,您需要在其上进行映射。lastTenImages.images不会产生任何东西。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67013045

复制
相关文章

相似问题

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