Я хочу перечислить пользователей и все комментарии пользователей в MongoDB. Является ли это возможным? - PullRequest
1 голос
/ 21 июня 2020

Я хочу перечислить пользователей и найти комментарии в другой коллекции, используя тот же запрос.

Это моя схема пользователей:

Schema({
    cod: {
        type: String,
        require: true
    },
    name: {
        type: String,
        required: true
    }
})

И это моя схема комментариев:

Schema({
    user: {
        type: Schema.Types.ObjectId, 
        ref: 'users'
    },
    post: {
        type: Schema.Types.ObjectId, 
        ref: 'posts'
    },
    comment: {
        type: String,
        required: true
    }
})

Я хочу получить вот такие:

 {
    _id: 5eee97c18b83e338bcbfa8f9,
    name: 'Cool Name',
    cod: 'CN001',
    comments: [{
         _id: ObjectId(...)
         post: ObjectId(...),
         comment: 'comment 1'
        },
        {
         _id: ObjectId(...)
         post: ObjectId(...),
         comment: 'comment 2'
        }
    ]
   
  }

возможно ли?

Спасибо!

1 Ответ

0 голосов
/ 21 июня 2020

вам может потребоваться изменить схему на:

Пользователи:

Schema({
    cod: {
        type: String,
        require: true
    },
    name: {
        type: String,
        required: true
    },
    comments: {
        type: Schema.Types.ObjectId, 
        ref: 'comments'
    }
})

Комментарии:

Schema({
    post: {
        type: Schema.Types.ObjectId, 
        ref: 'posts'
    },
    comment: {
        type: String,
        required: true
    },
    user: { // in case you want to query comments and populate the user
        type: Schema.Types.ObjectId, 
        ref: 'users'
    }
})

Затем запрос:

users.findById({'your user id here'})
.populate({path:'comments',select:['post','comment']})
.then((response)=>{
 // do anything you want with the data here
})
...