我要解决的是:使用这个建议的方法(mapReduce)保存我的Ids数组的顺序和$ in: Does MongoDB's $in clause guarantee order
我已完成作业,并认为将它们转换为字符串是理想的: Comparing mongoose _id and strings
代码:
var dataIds = [ '57a1152a4d124a4d1ad12d80',
'57a115304d124a4d1ad12d81',
'5795316dabfaa62383341a79',
'5795315aabfaa62383341a76',
'57a114d64d124a4d1ad12d7f',
'57953165abfaa62383341a78' ];
CollectionSchema.statics.all = function() {
var obj = {};
//adds dataIds to obj.scope as inputs , to be accessed in obj.map
obj.scope = {'inputs': dataIds};
obj.map = function() {
//used toString method as suggested in other SO answer, but still get -1 for Id.
var order = inputs.indexOf(this._id.toString());
emit(order, {
doc : this
});
};
obj.reduce = function() {};
obj.out = {inline: 1};
obj.query = {"_id": {"$in": dataIds } };
obj.finalize = function(key, value) {
return value;
};
return Product
.mapReduce(obj)
.then(function(products){
console.log('map products : ', products)
})
};
这是我在产品承诺中继续使用console.log的原因:
[{ _id: -1, value: null } ]
其中,让我相信它无法通过dataIds的索引来匹配此对象的ObjectId。但是,如果我只是在.find()中使用$ in子句,则返回正确的产品 - 但是,顺序不正确。
用这个来获得意想不到的行为。
obj.map = function() {
for(var i = 0; i < inputs.length; i++){
if(inputs[i] == this._id.toString()){
}
emit(inputs[i], this);
}
};
发出:
[ { _id: '5795315aabfaa62383341a76', value: null },
{ _id: '57953165abfaa62383341a78', value: null },
{ _id: '5795316dabfaa62383341a79', value: null },
{ _id: '57a114d64d124a4d1ad12d7f', value: null },
{ _id: '57a1152a4d124a4d1ad12d80', value: null },
{ _id: '57a115304d124a4d1ad12d81', value: null } ]
obj.map = function() {
for(var i = 0; i < inputs.length; i++){
if(inputs[i] == this._id.toString()){
var order = i;
}
emit(this._id.toString(), this);
}
};
发出:
[ { _id: 'ObjectId("5795315aabfaa62383341a76")', value: null },
{ _id: 'ObjectId("57953165abfaa62383341a78")', value: null },
{ _id: 'ObjectId("5795316dabfaa62383341a79")', value: null },
{ _id: 'ObjectId("57a114d64d124a4d1ad12d7f")', value: null },
{ _id: 'ObjectId("57a1152a4d124a4d1ad12d80")', value: null },
{ _id: 'ObjectId("57a115304d124a4d1ad12d81")', value: null } ]
现在,我如何摆脱ObjectId()包装器?最好是比str.slice()更干净的东西,它可以工作 - 但是,我觉得必须有一个更“mongo”/更安全的转换Id的方式。
我查看了文档,但它只提到了toString()方法,它在地图中似乎无法正常工作:https://docs.mongodb.com/manual/reference/method/ObjectId.toString/
答案 0 :(得分:1)
想通了:
obj.map = function() {
for(var i = 0; i < inputs.length; i++){
if(this._id.equals(inputs[i])) {
var order = i;
}
}
emit(order, {doc: this});
};