gpt4 book ai didi

javascript - 如何转换 mongo ObjectId .toString 而不包含 'ObjectId()' 包装器——仅包含值?

转载 作者:太空宇宙 更新时间:2023-11-04 00:36:13 27 4
gpt4 key购买 nike

我想要解决的是:使用建议的方法(mapReduce)保留 $in 中的 Id 数组的顺序: 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)
})
};

这是我在产品 promise 中不断从 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});
};

关于javascript - 如何转换 mongo ObjectId .toString 而不包含 'ObjectId()' 包装器——仅包含值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38856374/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com