我正在使用MongoDB领域构建一个应用程序。应用程序存储有关用户的运动卡的信息(每个卡都有一个
cardId
卡迪德
.
这个过程是有效的(尽管我的代码可能是劣质的!)蒙哥的文件看起来像:
{
"_id": {
"$oid": "5f6a5bda82c81067eac32da6"
},
"itemId": "174428279769",
"cardId": [
"Was-Ant-5281"
],
"galleryURL": "https://thumbs2.ebaystatic.com/m/m1heSnR2qz5NbPw7mCxQhkg/140.jpg",
"title": "2020 Black Silver Ink 3-Color Rookie Patch Auto #229 Antonio Gibson #54//99"
}
因为另一个用户生成返回相同ebay的ebay API请求是可行的
itemId
,在我的代码中,我试图检查是否存在具有相同
项目ID
如果真的加上
卡迪德
而不是生成新文档。
我读过一些类似的问题,所以建议我用哪一个
$addToSet
具有
$set
但是当我试着这样做的时候,我会得到一些错误,比如
uncaught promise rejection: multiple write errors: [{write errors: [{Updating the path 'cardId' would create a conflict at 'cardId'}]}, {<nil>}]
.
下面是完整的代码-有人能建议正确的方法吗?
exports = async function(payload) {
const axios = require("axios");
const mongodb = context.services.get("mongodb-atlas");
const eventsdb = mongodb.db("cards");
const eventscoll = eventsdb.collection("ebay-prices");
//////////// Get a list of a users cards from the cards collection
var collection = context.services.get("mongodb-atlas").db("cards").collection("stuart collection");
var ownedCards = await collection.find({
forTrade: "Yes"
}).toArray();
for (let card of ownedCards) {
// make the ebay API call based on card brand, card series and player name
let url = "http://svcs.ebay.com/services/search/FindingService/v1?GLOBAL-ID=EBAY-US&REST-PAYLOAD&keywords=" + card.brand + " " + card.series + " " + card.player +
"&itemFilter(0).name=SoldItemsOnly&itemFilter(0).value=true&OPERATION-NAME=findCompletedItems&paginationInput.entriesPerPage=6&paginationInput.pageNumber=1&RESPONSE-DATA-FORMAT=json&SECURITY-APPNAME=<MyAPPID>&SERVICE-NAME=FindingService&SERVICE-VERSION=1.12.0";
let cardId = card.card_id;
axios
.get(url)
.then(resp => {
for (const item in resp.data.findCompletedItemsResponse[0].searchResult[0].item) {
const itemId = resp.data.findCompletedItemsResponse[0].searchResult[0].item[item].itemId[0];
const title = resp.data.findCompletedItemsResponse[0].searchResult[0].item[item].title[0];
const galleryURL = resp.data.findCompletedItemsResponse[0].searchResult[0].item[item].galleryURL[0];
const result = eventscoll.updateOne({
itemId: itemId
}, {
// $addToSet: { cardId: { $each: cardId } },
$set: {
itemId: itemId,
title: title,
cardId: [cardId],
galleryURL: galleryURL
}
}, {
upsert: true
})
}
})
}
};