Title: How to check if a user id exists in the array before adding?
Tags: node.js;mongodb;mongoose
Question: I have 2 models (TweetModel and RatingModel), and I want to add new user IDs to array retweets that have RatingModel, but I need to check if a user id exists in the array before adding to DB.
I will be grateful for the answer
RatingModel.findByIdAndUpdate(tweetId, { $push: { retweets: user._id } }).exec(async (err) =&gt; {
if (err) {
res.status(422).send()
} else {
res.json({
status: 'successful retweet',
data: await TweetModel.findById(tweetId),
})
}
})
RATING MODEL IN MONGODB
Comment: I just found a method exists(). Seems to work fine. Can i use it? `const isExist = await RatingModel.exists({ _id: tweetId, retweets: user._id })` //true or false

Comment: use `findOneAndUpdate` with not equal to condition, `findOneAndUpdate({ _id: tweetId, "retweets": { $ne: user._id } }, ....`

Comment: You could use $addToSet instead of $push.



{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 0, 'CommentCount': 3, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2021:00:05/20/21', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<node.js><mongodb><mongoose>', 'Title': 'How to check if a user id exists in the array before adding?', 'ViewCount': 49, 'id': 67619281, 'user_AboutMe': '', 'user_AccountId': 20710349.0, 'user_DisplayName': 'Alexander', 'user_Reputation': 5.0, 'user_Views': 5.0, 'user_id': 15207120.0}}