Mongoose引用返回一个空数组。

huangapple go评论55阅读模式
英文:

Mongoose referencing return an empty array

问题

我遇到一个问题,我无法解决,我已经创建了一个使用mongoose的express API,其中包含两个模型 "Posts" 和 "users"。

我想要的是,如果我执行GET请求到/posts,返回一个带有相关作者的帖子列表,如果我执行GET请求到/users,返回一个带有相关帖子的用户列表。

第一个请求正常工作,"authors" 被正确地填充。

第二个请求始终返回一个空的 "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: '服务器内部错误'
            })
    }
})
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: '服务器内部错误'
            })
    }
})

一切似乎都正确,但出于某种原因,我始终获得空数组。

英文:

i'm facing a problem that i'm not able to solve, i've created an express API with mongoose, with 2 models "Posts" and "users"

what i want is that if i perform a GET request to /posts return a lists of posts with the related author, and if i perform a GET request to /users return a lists of users with the related posts

well, the first one works fine, the "authors" is populated correctly.

the second one return always the "posts" array empty.

here my posts model:

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');

and here my Users model:

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' )

and here the respective 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'
            })
    }
})

All seems correct but for some reason, i get always the array empty.

答案1

得分: 1

你的路由和模型看起来都没问题。我猜你在创建帖子时没有将post._id添加到用户的posts数组中。如果你正确地将创建的post._id添加到用户的帖子中,它应该可以正常工作。

代码应该像这样:

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

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

Your routes and models seems to be ok. I guess you are not adding the post._id to the user.posts array when you create the Post. If you add the created post._id to the user posts correctly, it should work.

The code should be something like this:

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

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

答案2

得分: 0

我已找到解决方案,如果有人需要答案:

在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
            })
    }
})
英文:

I've found a solution by myself, if someone need the answer is:

in the userSchema simply add:

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

and then when the new post is created

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
            })
    }
})

huangapple
  • 本文由 发表于 2023年5月26日 17:18:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76339371.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定