Mongoose引用返回空数组

fjnneemd  于 2023-05-29  发布在  Go
关注(0)|答案(2)|浏览(162)

我正面临着一个我无法解决的问题,我用mongoose创建了一个express API,有两个模型“Posts”和“users”
我想要的是,如果我对/posts执行GET请求,则返回具有相关作者的帖子列表,如果我对/users执行GET请求,则返回具有相关帖子的用户列表
好吧,第一个工作正常,“作者”填充正确。
第二个总是返回“posts”数组为空。
这里我的帖子模型:

const mongoose = require('mongoose')

const PostsModel = new mongoose.Schema({
    title: {
        type: String,
        required: true,
    },
    content: {
        type: String,
        required: true,
    },
    img: {
        type: String,
        required: false,
        default: 'https://picsum.photos/1920/1080',
    },
    author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'userModel',
    },
    rate: {
        type: Number,
        required: false,
    },
}, { timestamps: true, strict: true });

module.exports = mongoose.model('postsModel', PostsModel, 'posts');

这里是我的用户模型:

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
    firstName: {
        type: String,
        required: true,
        max: 255
    },
    lastName: {
        type: String,
        required: true,
    },
    email: {
        type: String,
        required: true,
    },
    password: {
        type: String,
        required: true,
    },
    role: {
        type: String,
        required: false,
        default: 'user'
    },
    age: {
        type: Number,
        required: false,
        default: 0
    },
    posts: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'postsModel',
    }],
}, {
    timestamps: true, strict: true
})

module.exports = mongoose.model('userModel', UserSchema, 'users' )

这里是相应的GET

router.get('/posts', async (req, res) => {
    const {page = 1, pageSize = 10} = req.query
    try {
        const post = await PostsModel.find()
            .populate('author', 'firstName lastName age email')
            .limit(pageSize)
            .skip((page - 1) * pageSize)

        const totalPosts = await PostsModel.count();

        res.status(200).send({
            count: totalPosts,
            currentPage: +page,
            totalPages: Math.ceil(totalPosts / pageSize),
            statusCode: 200,
            post
        })
    } catch (error) {
        res.status(500)
            .send({
                statusCode: 500,
                message: 'Errore interno del server'
            })
    }
})
router.get('/users',  async (req, res) => {
    const { page = 1, pageSize = 30 } = req.query
    try {
        const users = await UsersModel.find()
            .populate('posts', 'title content')
            .limit(pageSize)
            .skip((page - 1) * pageSize)

        const totalUsers = await UsersModel.count()

        res.status(200).send({
            count: totalUsers,
            currentPage: page,
            totalPages: Math.ceil(totalUsers / pageSize),
            pageSize,
            users
        })
    } catch (error) {
        res.status(500)
            .send({
                message: 'Errore interno del server'
            })
    }
})

一切似乎都是正确的,但由于某种原因,我总是得到空数组。

e5nszbig

e5nszbig1#

你的路线和模型似乎是好的。我猜你在创建Post的时候没有把post._id添加到user.posts数组中。如果你将创建的post._id正确地添加到用户posts中,它应该可以工作。
代码应该是这样的:

const newPost = await PostsModel.create(req.body);

    const userPush = await UsersModel.findByIdAndUpdate(req.body.author, {
        $push: {
            posts: newPost._id,
        },
    });
ugmeyewa

ugmeyewa2#

我自己找到了一个解决办法,如果有人需要的答案是:
在userSchema中添加:

posts: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'postsModel',
        default: []
    }]

然后当新帖子创建时

router.post('/posts/new', async (req, res) => {
    const user = await UsersModel.findOne({ _id: req.body.author });

    const newPost = new PostsModel({
        title: req.body.title,
        content: req.body.content,
        author: user._id,
        img: req.body.img,
        rate: req.body.rate,
    })

    try {
        const post = await newPost.save()
        await UsersModel.updateOne({ _id: user._id }, {$push: {posts: post }})
        res.status(200)
            .send({
                message: 'Post salvato correttamente',
                statusCode: 200,
                post
            })
    } catch(error) {
        res.status(500)
            .send({
                message: 'Errore interno del server',
                statusCode: 500
            })
    }
})

相关问题