如何转换mongo ObjectId .toString不包括'ObjectId()'包装 – 只是值?

我想要解决的是:使用这个build议的方法(mapReduce)保存我的ID数组$ in的顺序: 是否MongoDB的$ in子句保证顺序

我做了功课,看到了将它们转换为string的理想select: 比较mongoose_id和string 。

码:

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 } ] 

这导致我相信它无法与来自此的ObjectId和dataIds的索引相匹配。 但是,如果我只是使用.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()方法,它似乎不能在map中正确工作: https : //docs.mongodb.com/manual/reference/method/ObjectId.toString/

弄清楚了:

  obj.map = function() { for(var i = 0; i < inputs.length; i++){ if(this._id.equals(inputs[i])) { var order = i; } } emit(order, {doc: this}); };