is there a way to prevent duplication of entries in neDB collection's array?

杀马特。学长 韩版系。学妹 提交于 2021-01-28 00:07:34

问题


var addNewUser = function (id, chatId) {
    db.update({ _id: id }, { $push: { users: chatId } }, {}, function (err, numAffected) {
        // code after the record is updated
    });
}

in this code I want to push new Id to the array if it is not in it.

I've read the docs of neDB but it seems there is no way to do that

I'm beginner so I think there is a way to do that but I cant see it.


回答1:


To push new chatId to users array only if it does not exist, you can use $addToSet. According to the nedb document:

$addToSet adds an element to an array only if it isn't already in it

Here is the example code:

var addNewUser = function (id, chatId) {
  db.update({ _id: id }, { $addToSet: { users: chatId } }, {}, function (err, numAffected) {
    // code after the record is updated
  });
}


来源:https://stackoverflow.com/questions/45895267/is-there-a-way-to-prevent-duplication-of-entries-in-nedb-collections-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!