1

This is my Schema:

let userSchema = new Schema({
    email: { type: String, required: true },
    password: { type: String, required: true },
    books: [{ cover: String, title: String, link: String }],
});

I am pushing an object to the books array, only if that object does not already exist. I don't understand why this does not work: I am saying find the user, check the books array to ensure that title does not exist add the new object to books array. However duplicates still show up in my array.

note: The query is being executed inside a function which is passed model, user, and an object containing the book data called info hence the info.title.

model.findOneAndUpdate(
    { email: user.email, 'books.title': { $ne: 'info.title  ' } },
    { $addToSet: { "books": { title: info.title, cover: 
    info.cover, link: info.link } } },
    { new: true },
    (err, user) => {
        if (err) throw err;
        console.log(user);
        }
    )

Appreciate the direction

JohnSnow
  • 6,911
  • 8
  • 23
  • 44

1 Answers1

2

From MongoDB $addToSet documentation https://docs.mongodb.com/manual/reference/operator/update/addToSet/#behavior

If the value is a document, MongoDB determines that the document is a duplicate if an existing document in the array matches the to-be-added document exactly; i.e. the existing document has the exact same fields and values and the fields are in the same order. As such, field order matters and you cannot specify that MongoDB compare only a subset of the fields in the document to determine whether the document is a duplicate of an existing array element.

You can also find a good answer here MongoDB - $addToSet on a list of Embedded Document

bappr
  • 175
  • 2
  • 9