Samantha Thomas Samantha Thomas - 1 month ago 7
Node.js Question

Add to array only if something isn't in it already?

I'm trying to insert a class into a classes array for a student, but only if the class isn't there already. I read upsert takes care of this, but it adds the class to the array whether it's already there or not. Can someone lead me in the right direction?

Student.findOneAndUpdate(
query,
{$push: {"classes": {class_id: class_id, class_title: class_title, class_instructor: class_instructor}}},
{safe: true, upsert: true},
callback
);

Answer

Use $ne

Student.findOneAndUpdate(
    {"classes.class_id":{$ne: class_id}}
    {$addToSet: {"classes": {class_id: class_id, class_title: class_title, class_instructor: class_instructor}}},
    {safe: true,},
    callback
)

;