簡體   English   中英

無法推送從貓鼬查詢返回的對象

[英]unable to push object returned from mongoose query

我正在制作社交媒體后端。 我將用戶添加的帖子保存在Post模型中,將用戶數據保存在User模型中。 GITHUB_REPO_LINK_AT_END

注意:UserSchema 有一個 Schema.TypesOf.ObjectId 引用到 POST 模型。 User_Model_&_Post_Model_are_provided_in_the_end

為了獲取特定用戶的所有帖子,我向路由“/post”發出 GET 請求,正文為:

{ "id" : "6399d54c00308a2fe0bdf9fc"} //sending user id to fetct all the ID of the post from USER model, so i can then query the POST model for the posts

這是我遇到問題的功能:

const getPost = async(req, res)=>{
    if(req.body.id){
        try {
            const user = await User.findById(req.body.id).select('-_id post');
            //THIS IS THE PART I NEED HELP WITH-------------------------------------------
            const posts = await user.post.map(async(postID) => {
                const result = await Post.findById(postID).select('-_id title body');
                //console.log(result) THIS PRINTS THE CORRECT OBJ FROM DB
                return result; //THIS RETURNS AN EMPTY OBJECT HERE
            });
            //----------------------------------------------------------------------------
            res.status(200).json(posts);
        } catch (error) {
            console.log(error);
            res.status(500).json({message: error.message});
        }
    }
};

發送 GET 請求時,它返回一個包含空對象的空數組。//PS:不。 空對象 = 實際編號數據庫中的對象

//This is the response 
[{},{},{},{},{},{},{},{},{},{},{}]
{
  //This is the user object
  "_id": "6399d54c00308a2fe0bdf9fc",
  "createdAt": "2022-12-14T13:52:40.483Z",
  "name": "ShivamUttam",
  "username": "Fadedrifleman",
  "post": [
    "6399d57200308a2fe0bdfa00",
    "6399d5c400308a2fe0bdfa06",
    "6399d5ca00308a2fe0bdfa0a",
    "6399d5d600308a2fe0bdfa0e",
    "6399de29e8aa8697299941c5",
    "6399dec6e9b79ac66c59cd7a",
    "6399df0dbea937f8b3365979",
    "6399df31bea937f8b336597d",
    "6399df31bea937f8b3365981",
    "6399df32bea937f8b3365985",
    "6399df33bea937f8b3365989"
  ],
  "__v": 5
}

USER 和 POST 的模型:

用戶:

const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
    createdAt: {
        type: Date,
        default: Date.now()
    },
    name: {
        type: String,
        required: [true, 'name must be provided'],
    },
    username : {
        type: String,
        required: [true, 'Username must be provided'],
    },
    post:[{
        type: mongoose.Schema.Types.ObjectId,
         ref: 'Post',
    }],
});
module.exports = mongoose.model('User', userSchema)

郵政:

const mongoose = require('mongoose')
const postSchema = new mongoose.Schema({
    createdAt: {
        type: Date,
        default: Date.now()
    },
    title:{
        type: String,
        required: [true, "title cannot be empty"],
        max: [20, "title cannot exceed 20 character"]
    },
    body: {
        type: String,
        max: [145, "body cannot exceed 145 character"],
    },
    tags:{
        type: String,
    },
});
module.exports = mongoose.model('Post', postSchema);

https://github.com/Fadedrifleman/socialMediaAppBackend/tree/master

由於您在 map 方法中使用了異步回調函數,因此異步函數總是返回一個承諾,無論該函數返回的實體都包含在一個承諾中並返回該承諾。

如果你想在異步js代碼中使用map函數,你可以試試下面的方法

const posts = await Promise.all(user.post.map(async(id)=>{
    const result = await Post.findById(postID).select('-_id title body');
    return result;
}));

如果你想直接發送帖子,你也可以在帖子上使用 .lean() 方法,如

await Post.findById(postID).select('-_id title body').lean()

你有一些可能會干擾的錯誤,我做了一個拉取請求來修復它們: https ://github.com/Fadedrifleman/socialMediaAppBackend/pull/1

但主要部分是這樣的:

const getPost = async (req, res) => {
    try {
        if (req.body.id) {
            const user = await User.findById(req.body.id);
            await user.populate("post");
            res.status(200).json(user.post);
            return;
        }

        const posts = await Post.find({ access: 'public' }).select('-access');
        res.status(200).json(posts);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM