Home > Blockchain >  How to insert value in a nested mongodb document?
How to insert value in a nested mongodb document?

Time:01-30

I have this document:

{
  "_id": {
    "$oid": "63cf19337c2df5fe442a2b69"
  },
  "createdAt": {
    "$date": {
      "$numberLong": "1674516787623"
    }
  },
  "updatedAt": {
    "$date": {
      "$numberLong": "1675035206032"
    }
  },
  "clientIp": "89.132.225.21",
  "products": {
    "6cc5a480-91f0-4aa8-975c-013d6bd155a3": {
      "currency": "EUR",
      "title": "VVV",
      "price": "12",
      "barionId": "[email protected]",
      "ratingTimeLength": 12
    }
  }
}

I would insert like this:

const userId = req.query.userId
            const productId = req.query.productId
            const token = authorization.slice(7)
            const userJWT = jwt.verify(token, process.env.JWT_SECRET) as JwtPayload
            const ObjectId = require('mongodb').ObjectId
            const id = new ObjectId().toHexString()
            await collection.updateOne(
                { _id: ObjectId(userId), [`products.${productId}`]: { $exists: true } },
                {
                    $set: {
                        [`products.$.payments.${id}`]: {
                            createdAt: new Date(),
                            createdBy: userJWT.userId,
                        },
                    },
                },
                { upsert: true }
            )

But it raise:

2023-01-29T23:43:33.653Z 1a42849c-d5aa-4127-8fdc-9169c1c6c405 ERROR MongoServerError: The positional operator did not find the match needed from the query.

When I query record in Compass, it returns the document:

{
"_id": ObjectId("63cf19337c2df5fe442a2b69"),
"products.6cc5a480-91f0-4aa8-975c-013d6bd155a3": {
"$exists": true
}
}

What is wrong?

CodePudding user response:

You should access the products property directly with:

await collection.updateOne(
  { _id: ObjectId(userId), [`products.${productId}`]: { $exists: true } },
  {
    $set: {
      [`products.payments.${id}`]: {
        createdAt: new Date(),
        createdBy: userJWT.userId,
      },
    },
  },
  { upsert: true }
);
  • Related