簡體   English   中英

Mongoose 如果不存在則創建多個文檔

[英]Mongoose create multiple document if not exists

我嘗試使用 MongoDB 和 Node express(第一次在 node.js 中)創建一個 API。

我做了以下路線,旨在使用 JSON 輸入(來自外部請求)在 mongoDB 中保存多個文件(唯一):

router.post('/sessions', function (req, res, next) {
    // invoke sessions update
    var config = {
        method: 'get',
        url: 'https://blabla',
        headers: {
            'Accept': 'application/json;version=0.1',
            'Accept-Language': 'fr',
        }
    };

    axios(config)
        .then(function (response) {
            for (const session of response.data) {
                doc = UserSimple.findOne({id: session.recipient.id}).then(function (doc) {
                    if (!doc) {
                        var newUser = new UserSimple(session.recipient)
                        newUser.save()
                    }
                })
            }
        })
        .catch(function (error) {
            console.log(error);
        });
});

從我的代碼來看,我似乎沒有正確理解“承諾”,因為我的代碼嘗試獲取所有文檔,然后將其保存(因為做出承諾時不存在)它在 MongoDB 中:

Mongoose: usersimples.findOne({ id: 146299 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11676365 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11427231 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11676365 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 146299 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11676365 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11676365 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 481020 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11427231 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11427231 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 146299 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11676365 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 481020 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 146299 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11676365 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11427231 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11676365 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 481020 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 146299 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11427231 }, { projection: {} })
Mongoose: usersimples.insertOne({ _id: ObjectId("60b8910526436428a409f6a9")....., id: 11676365 })
...
Mongoose: usersimples.insertOne({ _id: ObjectId("60b8910526436428a409f6ab")....., id: 11676365 })

我想要做的是,檢查MongoDB中是否存在一個文件,如果沒有則創建它; 因此,在同一個“請求”中,如果我的 JSON 輸入中有重復項,則只會創建唯一的文檔。 我想這種“問題”很常見,但我沒有找到任何資源來解決它。

謝謝您的幫助

不等待您的save ,因此您最終可能會遇到一個文檔尚未保存的情況,而循環繼續處理其他 JSON 文檔,可能與正在保存的文檔相同。

使用 async/await 重寫:

try {
    const response = await axios(config);
    let doc;
    for (const session of response.data) {
        doc = await UserSimple.findOne({ id: session.recipient.id });
        if (!doc) {
            var newUser = new UserSimple(session.recipient);
            await newUser.save();
        }
    }

} catch (error) {
    console.log(error);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM