search

Home  >  Q&A  >  body text

mongodb - mongoose how to query multiple models

for example

aModel = {
    user_id: String,
    file_name: String,
    page_id: Number
}
fileSchema = new Schema({
    page_id: Number,
    key: String,
    doc: String,
    title: String,
    sym: String
});

bModel = {
    user_id: String,
    file_name: String,
    origin_file: String,
    new_file: [fileSchema]
}

It is known that user_id, file_name, page_id and model are asynchronous. How to search these two models at the same time?
Go to the next step after getting two results

欧阳克欧阳克2705 days ago1060

reply all(4)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-06-20 10:07:55

    The code is as follows. In fact, I feel that the writing is not elegant at all...

    var aDocs ,bDocs =null ;
    aModel.find({ user_id:xx , file_name:xx , page_id:xx})
        .then(function(docs){
            aDocs = docs;
            return bModel.find({ user_id:xx , file_name:xx , page_id:xx}) })
        .then(function(docs){
            bDocs = docs ;
            other codes
        })

    reply
    0
  • 女神的闺蜜爱上我

    女神的闺蜜爱上我2017-06-20 10:07:55

    If you need them to execute concurrently, you can use Promise

    const query1 = aModel.find(query)
    const query2 = bModel.find(query)
    Promise.all([query1, query2]).then(rs => {})
    

    If you don’t need to do it concurrently and can do it synchronously, you can use yield or async/await

    const query1 = yield aModel.find(query)
    const query2 = yield bModel.find(query)
    
    // 需要node7以上
    const query1 = await aModel.find(query)
    const query2 = await bModel.find(query)
    

    reply
    0
  • 女神的闺蜜爱上我

    女神的闺蜜爱上我2017-06-20 10:07:55

    Of course the upstairs is not very elegant. What you need is async/await, so upgrade node to 7.6 or above

    reply
    0
  • 世界只因有你

    世界只因有你2017-06-20 10:07:55

    Really? Doesn't the mongoose api have a method for multi-table query?

    reply
    0
  • Cancelreply