【问题标题】:mongoose : find data by looping on an array of models猫鼬:通过在模型数组上循环查找数据
【发布时间】:2014-08-02 20:03:00
【问题描述】:

我被异步算法卡住了:

我有一系列猫鼬模型:

var allRefDatasSchemas = {
  RefAllotement: mongoose.model('RefAllotement', RefDataSchema),
  RefModeleConstructeur: mongoose.model('RefModeleConstructeur', RefDataSchema),
  RefTypeKit: mongoose.model('RefTypeKit', RefDataSchema),
  RefTypeUtilisation: mongoose.model('RefTypeUtilisation', RefDataSchema),
};

我想抓取每个集合的所有项目并将它们放入一个数组或类似的东西中。 如果我这样做,find 回调的 this 关键字不会引用当前模型, 我不可能知道属于哪个模型项目

var results = {};

for (var model in allRefDatasSchemas) {

  allRefDatasSchemas[model].find(function(err, data) {

    // I'd like to do something like that :
    // but this.modelName is null, because it isn't the model
    // on which the find is done.
    results[this.modelName] = data;

    // if I use "model" variable, it doesn't work, because asynchronous callback

  });

}

我也尝试过async 库但没有成功,因为我总是回到同样的问题:不可能知道哪个模型在回调中执行 find 查询。 如果我使用 Promise,则在 then 中同上。

请帮助我 :) 你会怎么做呢?

编辑 model.find 调用 query.find,query.find 调用 mquery.find。在 mquery.find 中,回调被调用,在那个时候丢失了 this 引用:this._collection.find(conds, options, utils.tick(callback)); /编辑

【问题讨论】:

  • 您可以编辑自己的问题以添加信息,而不是发布 cmets。我真的不明白您为什么要这样做,因为您肯定可以以不同的方式建模。但是async 系列应该适合你,除了那不是你发布的代码。
  • 是的,我了解您关于建模的问题:我的目标是在主干客户端应用程序上一次加载一些 refdata(选择输入中使用的数据)(关注this pattern):)

标签: node.js mongodb mongoose


【解决方案1】:

请检查此代码 sn-p,我已经制作了您需要的工作示例。 请检查代码中的 cmets 以便更好地理解。

Sample Working code 与您的要求类似。另一个 ref ques 用于将 async 与 mongoose 一起使用。

/*
 * Object to store all models
 */
var allRefDatasSchemas = {
  RefAllotement: mongoose.model('RefAllotement', RefDataSchema),
  RefModeleConstructeur: mongoose.model('RefModeleConstructeur', RefDataSchema),
  RefTypeKit: mongoose.model('RefTypeKit', RefDataSchema),
  RefTypeUtilisation: mongoose.model('RefTypeUtilisation', RefDataSchema),
};
/*
 * need an array to run all queries one by one in a definite order using async waterfall mwthod
 */
var arr = [];
for(each in allRefDatasSchemas) {
    arr.push(each);
}

/*
 * Callback function for initiation of waterfall
 */
var queue = [
    function(callback) {
        // pass the ref array and run first query by passing starting index - 0
        callback(null, arr, 0)
    }
];

/*
 * Object to store result of all queries
 */
var finalResult = {};

/*
 * Generic Callback function for every dynamic query
 */
var callbackFunc = function(prevModelData, currentIndex, callback) {
    allRefDatasSchemas[arr[currentIndex]].find(function(err, result) {
        if(err) {
            console.log(err)
        } else {

            // Your Query
            // 
            // I'd like to do something like that :
            // but this.modelName is null, because it isn't the model
            // on which the find is done.

            // arr[currentIndex] will point to 
            // RefAllotement, RefModeleConstructeur etc. as you required
            finalResult[arr[currentIndex]] = result

            // send current result to next interation if required or you can skip
            // and increment the currentIndex to call next query 
            callback(null, result, currentIndex + 1)
        }
    })
}

/*
 * Add callback function for every dynamic query
 */
for(each in allRefDatasSchemas) {
    queue.push(callbackFunc);
}

/*
 * Run all dynamic queries one by one using async.js waterfall method
 */
async.waterfall(queue, function (err, result) {
    // Final object with result of all the queries
    console.log('finish', finalResult)
});

输出将采用这种格式

finish { RefAllotement:[
        // Result of RefAllotement query
    ],
    RefModeleConstructeur:[
        // Result of RefModeleConstructeur query
    ],
    RefTypeKit:[
        // Result of RefTypeKit query
    ],
  RefTypeUtilisation:[
        // Result of RefTypeUtilisation query
    ]
}

【讨论】:

  • 太棒了!我唯一缺少的是创建带有索引模型名称的第二个数组!有了它,我可以知道 find 回调中的模型名称(finalResult[arr[currentIndex]] = result)。非常感谢您的明确回复!
  • 也谢谢你,我的第一个问题被 StackOverflow 接受了
猜你喜欢
  • 2021-10-17
  • 1970-01-01
  • 2016-03-31
  • 2023-01-30
  • 2021-01-24
  • 2020-09-12
  • 2021-04-03
  • 2016-05-14
  • 1970-01-01
相关资源
最近更新 更多