mongoose MongoDB如何从模型数组中提取id对象?

wtzytmuj  于 2023-01-05  发布在  Go
关注(0)|答案(1)|浏览(151)

我有一个名为"Popular"的模型,其中有一个名为"PopularPosts"的数组,我在其中存储来自模型"Post"的Postid。
流行车型

const mongoose = require('mongoose');

const PopularSchema = new mongoose.Schema(
    {
        PopularPosts: [{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Post',
            required: false,
        }],
        createdAt: {
            type: Date,
            default: Date.now,
        }
    },
    { timestamps: true }
  );
  
module.exports = mongoose.model("Popular", PopularSchema);

员额

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

但是,当我执行get请求时,我只从数组返回id,而不是所有post信息。因此,我尝试创建一个Populate,以便在发出请求时提取每个id的post信息

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

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

        try {
            const popularPosts = await Popular.findById({id}).populate({
                path: 'PopularPosts',
                model: 'Post', 
            }).lean();

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

module.exports = new FindPopularPosts();

Postman 错误:

{
    "stringValue": "\"{ id: '63b5a895fbb93698183d75d2' }\"",
    "valueType": "Object",
    "kind": "ObjectId",
    "value": {
        "id": "63b5a895fbb93698183d75d2"
    },
    "path": "_id",
    "reason": {},
    "name": "CastError",
    "message": "Cast to ObjectId failed for value \"{ id: '63b5a895fbb93698183d75d2' }\" (type Object) at path \"_id\" for model \"Popular\""
}
e3bfsja2

e3bfsja21#

如果你试着像这样查询你的热门帖子,你会得到什么?

const { id } = req.params;
 try {
        const popularPosts = await Popular.findById(id).exec();

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

更新:我认为问题出在Schema中,请更改此处的类型:

const PopularSchema = new mongoose.Schema(
    {
        PopularPosts: [{
            type: mongoose.Schema.Types.ObjectId, // the prob is here, change the right type here, if your post is a string than : string.
            ref: 'Post',
            required: false,
        }],
        createdAt: {
            type: Date,
            default: Date.now,
        }
    },
    { timestamps: true }
  );

相关问题