[英]How to insert value in a nested mongodb 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": "aa@aa.hu",
"ratingTimeLength": 12
}
}
}
我會這樣插入:
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 }
)
但它提出:
2023-01-29T23:43:33.653Z 1a42849c-d5aa-4127-8fdc-9169c1c6c405 錯誤 MongoServerError:位置運算符未從查詢中找到所需的匹配項。
當我在 Compass 中查詢記錄時,它返回文檔:
{
"_id": ObjectId("63cf19337c2df5fe442a2b69"),
"products.6cc5a480-91f0-4aa8-975c-013d6bd155a3": {
"$exists": true
}
}
怎么了?
您應該直接訪問products
屬性:
await collection.updateOne(
{ _id: ObjectId(userId), [`products.${productId}`]: { $exists: true } },
{
$set: {
[`products.payments.${id}`]: {
createdAt: new Date(),
createdBy: userJWT.userId,
},
},
},
{ upsert: true }
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.