如何从Mongoose中的数组中获取对象信息?

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

How to receive object information from within an array in mongoose?

问题

Category模型中有一个存储postId的数组。您想要在返回的数据中包含每个post的信息,如下所示:

{
    "_id": "63ac925d872445065a588f61",
    "name": "Games",
    "color": "#ff914d",
    "posts": [
        {
            "name": "red dead",
            "img": "example.png",
            "category": "games",
            "desc": "test"
        }
    ],
    "createdAt": "2022-12-28T19:00:45.847Z",
    "updatedAt": "2022-12-28T19:49:47.119Z",
    "__v": 0
}

这需要您在查询Category时使用Mongoose的populate方法,以便在返回的数据中包含关联的Post信息。以下是如何修改您的代码:

const Category = require('../../models/Category');

class FindCategory {
    async find(req, res) {
        const { id } = req.params;

        try {
            const category = await Category.findById(id).populate('posts');

            return res.status(200).json(category);
        } catch (err) {
            return res.status(500).json(err);
        }
    }
}

module.exports = new FindCategory();

通过添加.populate('posts'),您将能够获取与Category相关联的所有Post的详细信息。

英文:

I have two models, a posts model and a category model where I have an array that stores posts by objectId

Category Model

const mongoose = require('mongoose');

const CategorySchema = new mongoose.Schema(
    {
        name: {
            type: String,
            required: true,
        },
        color: {
            type: String,
            required: true,
        },
        posts: [{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Post',
            required: false,
        }],
        createdAt: {
            type: Date,
            default: Date.now,
        }
    },
    { timestamps: true }
  );
  
module.exports = mongoose.model("Category", CategorySchema);

Post model

const mongoose = require('mongoose');

const PostSchema = new mongoose.Schema(
    {
        title: {
            type: String,
            required: true,
        },
        img: {
            type: String,
            required: true,
        },
        category: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Category",
        },
        desc: {
            type: String,
            required: false,
        },
        createdAt: {
            type: Date,
            default: Date.now,
        }
    },
    { timestamps: true }
  );
  
module.exports = mongoose.model("Post", PostSchema);

So I created a get by id category controller

const Category = require('../../models/Category');

class FindCategory {
    async find(req, res) {
        const { id } = req.params;

        try {
            const category = await Category.findById(id);

            return res.status(200).json(category);
        } catch (err) {
            return res.status(500).json(err);
        }
    }
} 

module.exports = new FindCategory();

The problem is that when I make this request in my postman, it returns me for example

{
    "_id": "63ac925d872445065a588f61",
    "name": "Games",
    "color": "#ff914d",
    "posts": [
        "63ac9cbccec4d9f35c4f4d1f"
    ],
    "createdAt": "2022-12-28T19:00:45.847Z",
    "updatedAt": "2022-12-28T19:49:47.119Z",
    "__v": 0
}

But I would like to render the information of each post inside the "posts" array, something like that for example

{
    "_id": "63ac925d872445065a588f61",
    "name": "Games",
    "color": "#ff914d",
    "posts": [
        "name": "red dead",
        "img": "example.png", 
        "category": "games",
        "desc": "test,
    ],
    "createdAt": "2022-12-28T19:00:45.847Z",
    "updatedAt": "2022-12-28T19:49:47.119Z",
    "__v": 0
}

答案1

得分: 1

你应该使用 mongoose 提供的 populate 函数:https://mongoosejs.com/docs/populate.html#setting-populated-fields

Category.
  findById(...).
  populate('posts')
英文:

You should use the populate function provided by mongoose: https://mongoosejs.com/docs/populate.html#setting-populated-fields

Category.
  findById(...).
  populate('posts')

huangapple
  • 本文由 发表于 2023年1月6日 01:34:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75022289.html
匿名

发表评论

匿名网友

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

确定