2016-09-06 29 views
0

我有一個productIdsProduct集合的數組。我想查詢productId數組中所有產品的產品集合 ,但是我希望結果與查詢數組的的訂單號相同。 ProductsIds使用其他參數,這些參數不是 ,可在產品集合的文檔中找到,因此我無法對產品集合進行排序。 有沒有辦法維持訂單? 例子:

productIds: [362,128,4783,1,44] 

db.collection('products'). find({id:{$in:productIds}}).toArray()我想要的文件是在順序的productIds 目前,我得到一個不同的順序。

回答

0

你有兩個簡單的選擇:

1)排序內存

const productIds = [362,128,4783,1,44]; 
const idAscending = (a, b) => productIds.indexOf(a.id) > productIds.indexOf(b.id); 

db.collection('products').find({ id:{ $in:productIds } }).toArray() 
.then(products => products.sort(idAscending)); 

2)製作單獨的查詢

const Promise = require('bluebird'); 
const productIds = [362,128,4783,1,44]; 

Promise.map(productIds, db.collection('products').findOne); 
+0

我選擇了在內存中的排序與我自己的分頁。 。不管怎樣,謝謝 –

相關問題