首页 > 解决方案 > 如何使子数组唯一

问题描述

我遇到以下问题

{
    artist:"Macy Gray"
    song:"I Try'"
    station:"PERTHRadio"
    timeplay:2020-07-17T10:39:00.000+00:00
     __v:0
     history:Array
     0:"7320564F-76B2-40D0-A0E8-E3917148F567"
     1:"7320564F-76B2-40D0-A0E8-E3917148F567"
}

基本上它在历史上添加了两次相同的 UUID。

我正在使用findOneAndUpdatewith $push

我正在使用的代码

const nowplayingData = {
    "station": req.params.stationname,
    "song": data[1],
    "artist": data[0],
    "timeplay":npdate
};
                
LNowPlaying.findOneAndUpdate(
    nowplayingData,
    { $push: { history: [uuid] } },
    { upsert: true },
    function(err) {
         if (err) {
            console.log('ERROR when submitting round');
            console.log(err);
         }
    }
);

标签: mongodbmongoose

解决方案


通常当人们遇到这样的问题时,这是因为代码所在的函数/路由正在运行两次。(再次 - 通常 - 这是由于调试器正在触发额外调用或类似的东西)。

无论您在调试时还是在生产中发生这种情况,您都可以开始使用$addToSet而不是 push,这将保证不会推送重复的值。

LNowPlaying.findOneAndUpdate(
   nowplayingData,
   { $addToSet: { history: [uuid] } },
   { upsert: true },
   function(err) {
        if (err) {
           console.log('ERROR when submitting round');
           console.log(err);
        }
   }
);

推荐阅读