我应该如何从另一个集合中获取数据并与结果合并

时间:2019-06-06 04:38:47

标签: node.js mongodb mongoose

我有一个端点,该端点为我提供了所有可用配置文件的列表,现在我有一个发布架构和配置文件架构,我想添加特定用户对我的结果发表的帖子的列表

端点中存在代码

 const profiles = await Profile.find()
            .populate('user', [
                'name',
                'avatar'
            ])

配置文件架构

const ProfileSchema = new mongoose.Schema({
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'user'
    },
    post: [],
    ........

发布架构

const PostSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'user'
    },
    text: {
        type: String,
        required: true
    },
    ........

回复

[
    {
        "social": {
            "youtube": "https://youtube.com/.",
            "twitter": "https://twitter.com/.",
            "facebook": "https://fb.com/."
        },
        "post": [],          //This should populate
        "skills": [
            "HTML",
            "CSS",
            "PHP",
            "Ruby"
        ],
        "_id": "5ced6cb9e3f7485ee2cb0445",
        "user": {
            "_id": "5ced02551b60fe20afc72a32",
            "name": "John abc",
            "avatar": "//www.gravatar.com/avatar/1f9d9a9efc2f523b2f09629444632b5c?s=200&r=pg&d=mm"
        },
        "status": "Developer",
        "experience": [
            {
                "current": true,
                "_id": "5ceebb30bb0c667b85a94f97",
                "from": "2010-08-09T18:30:00.000Z",
                "description": "lorem ipasum"
            }
        ],
        "date": "2019-05-28T17:15:37.755Z",
        "__v": 30,
        "bio": "I am dev",
        "education": [
            {
                "current": false,
                "_id": "5cf0c1dc6b8dc33cd68be560",
                "degree": "BE",
                "from": "2005-07-09T18:30:00.000Z",
                "to": "2010-03-03T18:30:00.000Z",
                "description": "Got BE"
            }
        ]
    }
]

预期产量

[
    {
        "social": {
            "youtube": "https://youtube.com/.",
            "twitter": "https://twitter.com/.",
            "facebook": "https://fb.com/."
        },
        "post": [
                 {_id:98as98djakjbkasd,
                  text:"This is post by xyz user"
                 },
                 {_id:234oijaoijd,
                  text:"This is another post by xyz user"
                 }
                ]
        "skills": [
            "HTML",
            "CSS",
            "PHP",
            "Ruby"
        ],
        "_id": "5ced6cb9e3f7485ee2cb0445",
        "user": {
            "_id": "5ced02551b60fe20afc72a32",
            "name": "John abc",
            "avatar": "//www.gravatar.com/avatar/1f9d9a9efc2f523b2f09629444632b5c?s=200&r=pg&d=mm"
        },
        .....

我想填充由同一用户完成的帖子,需要在终结点代码中进行哪些更改。

我是猫鼬的新手,在寻找解决方案时,我发现aggregate可能有用,但不能像.find().aggregate([...])那样使用

0 个答案:

没有答案