简体   繁体   English

从 mongodb 获取数据时,节点 js javascript 中的 Map.get() 总是返回 undefined

[英]Map.get() in node js javascript always return undefined while fetching data from mongodb

I am using a map here in which I stored id:quantity pair I want to add this quantity to each item of products array (containing objects) and I am getting this quantity through map.get(id) method, despite the type of id and the id passed into get function are of same value and data type,I am getting undefined, I tried to verify the type and value of id in map and id passed, both are same.still the problem exists我在这里使用 map 存储 id:quantity 对 我想将此数量添加到 products 数组的每个项目(包含对象)中,并且我通过 map.get(id) 方法获取此数量,尽管 id 的类型并且传递给 get function 的 id 具有相同的值和数据类型,我越来越不确定,我试图验证 map 中 id 的类型和值和传递的 id,两者都是相同的。问题仍然存在

this is the faulty code, actually I am returning a promise through this function这是错误代码,实际上我正在通过此 function 返回 promise

var cartMap = new Map();
for (let i = 0; i < this.cart.items.length; i++) {
    const e = this.cart.items[i];
    cartMap.set(mongodb.ObjectId(e._id), e.quantity);
}
db.collection("products").find({ _id: { $in: [...productIds] } }).toArray().then((products) => {
    console.log(cartMap);
    let newProd = products.map(prod => {
        console.log(cartMap.get(prod._id)); // returns undefined
        prod.quantity = cartMap.get(prod._id);
        // cartMap.set(prod._id, -1);
        return prod;
    })
    console.log(newProd);
    if (productIds.length > products.length) {
        let garbageCart = cartMap.keys().filter(prod => {
            if (cartMap.get(prod) != -1) {
                return prod;
            }
        })
        garbageCart.sort();
        this.cart.items.sort();
        let i = 0;
        let updatedCart = this.cart.items.filter(prod => {
            if (i >= garbageCart.length) {

            }
            else if (prod._id == garbageCart[i]) {
                i++;
            }
            else {
                return prod;
            }
        })
        db.collection("users").updateOne({ _id: this.id }, {
            $set: { cart: updatedCart }
        })
    }
    resolve(newProd);

console messages控制台消息

Map(2) { 608c49bca4d1ed0bfc8c41fb => 1, 608c4a41a4d1ed0bfc8c41ff => 1 }
undefined
undefined
[
  {
    _id: 608c49bca4d1ed0bfc8c41fb,
    title: 'chhole bhature',
    description: 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Qui dolor ratione officia quam magni sed, consequuntur maiores illo labore quas molestiae suscipit asperiores beatae voluptatem saepe commodi explicabo perspiciatis non sequi in praesentium illum, nesciunt iste.',   
    price: '1000',
    imageurl: 'imageurl',
    userId: null,
    quantity: undefined
  },
  {
    _id: 608c4a41a4d1ed0bfc8c41ff,
    title: 'hat',
    description: 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Qui dolor ratione officia quam magni sed, consequuntur maiores illo labore quas molestiae suscipit asperiores beatae voluptatem saepe commodi explicabo perspiciatis non sequi in praesentium illum, nesciunt iste.',   
    price: '478',
    imageurl: 'imageurl',
    userId: null,
    quantity: undefined
  }
]

This is because mongodb.ObjectId(e._id) on one hand, and prod._id on the other hand, are references to two different locations in memory, and as such they will not compare as equal to each other - even though I understand the objects available at these locations represent the same ObjectId .这是因为mongodb.ObjectId(e._id)prod._id是对 memory 中两个不同位置的引用,因此它们不会相互比较 - 即使我理解在这些位置可用的对象代表相同的ObjectId

To further illustrate this point in the context of the map() usage:为了在map()使用的上下文中进一步说明这一点:

var map = new Map()
// object1 and object2 represent the same object, but point to different locations in memory
var object1 = createObject()
var object2 = createObject()

map.set(object1, "some value")

console.log(map.get(object1))   // output: "some value"
console.log(map.get(object2))   // output: undefined

function createObject() {
    return {
        key: "value"
    }
}

You could instead use those objects string representations as the keys for the map - by converting them using their ObjectId.toString() method.您可以改为使用这些对象字符串表示作为 map 的键 - 通过使用它们的ObjectId.toString()方法转换它们。 Since they are value - as opposed to reference - types, strings representing the same sequence of characters will compare as equal to each other.由于它们是值 - 而不是引用 - 类型,表示相同字符序列的字符串将相互比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM