在mongo里, 用聚合函数写一个聚合搜索常常会用到$unwind, 用来把document里的数组展平。比如
{ _id : 1, item : "ABC1", sizes: [{_id:"123",size:"S"},{_id:"123",size:"M"}] };,展平得到:
[ { _id: 1, item: 'ABC1', sizes: { _id: '123', size: 'S' } },
{ _id: 1, item: 'ABC1', sizes: { _id: '123', size: 'M' } } ]
用nodejs的时候,常用工具lodash里并没有提供类似于unwind这样的方法,你当然可以遍历这个数组,依次展开最后生成一个新的数组出来,但还有下面这种比较好的方法,利用到_.mixin()
Adds all own enumerable string keyed function properties of a source object to the destination object. If object is a function, then methods are added to its prototype as well.
你可以先定义好自己的函数,然后传入_.mixin()去绑定一个名称,比如unwind,这样你就可以在当前的进程里用_.unwind(x,y)来处理你的数据了。
let _=require('lodash')
function unwind(o, field){
return _.map(o[field], function(val) {
var cloned = _.clone(o);
cloned[field] = val;
return cloned;
})
}
_.mixin({'unwind':unwind});
//-test-
var o = { _id : 1, item : "ABC1", sizes: [{_id:"123",size:"S"},{_id:"123",size:"M"}] };
console.log(_.unwind(o, 'sizes'))
//-result-
//[ { _id: 1, item: 'ABC1', sizes: { _id: '123', size: 'S' } },{ _id: 1, item: 'ABC1', sizes: { _id: '123', size: 'M' } } ]
//-----------------------如果方法体不大,直接写入\_.mixin()也可以-------------
_.mixin({
unwind: function(o, field) {
return _.map(o[field], function(val) {
var cloned = _.clone(o);
cloned[field] = val;
return cloned;
});
}
});
var o = { _id : 1, item : "ABC1", sizes: [ "S", "M", "L"] };
log(_.unwind(o, 'sizes'));
网友评论