[英]Mongoose multiple synchronous find to reuse object ID
我的模型在每個對象之間有很多關系,當我想搜索一些數據時,我必須找到前一個對象,這使我編寫了很多回調。
我有4個型號:
然后,我需要通過緯度/經度來獲取最近的用戶及其信息(姓名,辦公室名稱,公司,名稱等...)。 這是來自地獄的結果回調。
// Find all Geolocation
Geolocation.find({}, function(err, geolocations) {
if (err) throw err;
var array = [];
// Loop on geolocations object
Async.each(geolocations, function(origin, callback){
var myJson = {"latitude":43.686978, "longitude":7.201922};
// Calculate distance between two points
var geo = geolib.getDistance(
{latitude: origin.latitude, longitude: origin.longitude},
{latitude: myJson.latitude, longitude: myJson.longitude}
);
// Find the office with the current geolocation object ID
Office.findOne({ geolocation: origin._id}, function(err, office){
if (err) throw err;
// Find the company with the current office object ID
Company.findOne({ _id: office.company }, function(err, company){
if (err) throw err;
// Find the user with the current office object ID
User.findOne({office: office._id}, function(err, user){
if (err) throw err;
array.push({
user: user.firstname+' '+user.lastname,
office: office.name,
company: company.name,
distance: geo
});
callback();
});
});
});
}, function(err) {
array.sort(function (a, b) {
return a.distance - b.distance;
});
for (var i = 0; i < array.length; i++){
console.log(array[i])
}
});
});
我正在使用異步,但是我不知道這是否是知道循環何時結束以及each()
方法是否最合適的好方法。
如您所見,我必須進行大量查找才能獲取對象ID,然后再次查找以獲取用戶的所有信息。
您是否有使我的代碼更整潔的想法? 還是我不應該在模型中使用對象ID?
您可以將每個findOne
函數包裝到promise中,並使用Babel中的await
。 在這種情況下,您的代碼可能如下所示:
let office = await new Promise((resolve, reject) => {
Office.findOne({ geolocation: origin._id}, function(err, office){
if (err) reject(err)
resolve(office)
});
let company = await new Promise((resolve, reject) => {
Company.findOne({ _id: office.company }, function(err, company){
if (err) reject(err)
resolve(company)
});
... and so on
或者,也許您想閱讀有關MongoDB中的人口的信息: http : //mongoosejs.com/docs/populate.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.