mongodb - 如何使子数组唯一
问题描述
我遇到以下问题
{
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。
我正在使用findOneAndUpdate
with $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);
}
}
);
解决方案
通常当人们遇到这样的问题时,这是因为代码所在的函数/路由正在运行两次。(再次 - 通常 - 这是由于调试器正在触发额外调用或类似的东西)。
无论您在调试时还是在生产中发生这种情况,您都可以开始使用$addToSet而不是 push,这将保证不会推送重复的值。
LNowPlaying.findOneAndUpdate(
nowplayingData,
{ $addToSet: { history: [uuid] } },
{ upsert: true },
function(err) {
if (err) {
console.log('ERROR when submitting round');
console.log(err);
}
}
);
推荐阅读
- python - 如何从 AWS Glue Python Shell 连接到 RDS 实例?
- java - 创建 EJB 提供程序 javax.persistence.PersistenceContext.synchronization()Ljavax/persistence/SynchronizationType
- python - 如何保留列表中的某些元素?
- python - 每次抓取后如何捕获“finish_reason”
- oracle - 使用 oracle cdc 时出现可写操作错误
- javascript - 如何使用 php for 循环创建 FilePond 实例,并使用插件
- c# - 错误:无法解析模块`api-ecommerce`
- jquery - 如何在不使用 Jquery 更改字体图标的情况下更改按钮名称
- asp.net-core - .Net 核心中用于标识符散列(不是密码)的 PBKDF2
- sql - ON CONFLICT DO UPDATE SET foo = NOT EXCLUDED.foo 没有按预期工作