Prevent duplicates in an array of objects

I'm learning Node / Mongoose, and trying to figure out how to prevent duplicates in an array of ListItems:

var listitemSchema = new mongoose.Schema({
   name: String,
   rank: Number
}); 

...which exist inside a user:

var userSchema = new mongoose.Schema({
    username: String,
    password: String,
    list: [{
        type: mongoose.Schema.Types.ObjectId,
     ref: "ListItem"
    }]  
});

...based on whether the user already has the name within his/her list. I was looking into $addtoset but can't really figure out how to put conditions when dealing with an object. The docs weren't very helpful and I can't seem to find similar examples online. Right now my 'POST' request is a mess and looks like this:

router.post("/editlist", isLoggedIn, function(req,res){
    User.findById(req.user._id).populate("list").exec(function(err , user) {
        if(err) {
            console.log(err);
            res.redirect("/editlist");
        } else {
            //prevent duplicates based on username
            User.update(
                { "_id": req.user._id },
                { $addToSet: { "streamName": req.body.listitem.name}
            });
            res.redirect("/watch");
         }
    });
});

Can anyone send me on my way? My $addToSet isn't pushing items onto the list array.

Answers


According to the $addToSet documentation, the operator is used in this form:

{ $addToSet: { field1: value1, ... } }

where field is an Array.

To add an item to the list array, we do:

User.update({
  { "_id": req.user._id },
  { $addToSet: { list: {"streamName": req.body.listitem.name } }}
});

You'll need to update the userSchema definition:

var userSchema = new mongoose.Schema({
    username: String,
    password: String,
    list: [listitemSchema]  
});

Need Your Help

Unspecified data type data parsing in Java

java android json

How would you parse the below string response data in Java?

Avoiding redefinition of a macro-defined class

c++ class macros

Is there a mechanism in C++ that I could use to implement a macro such that the macro defines a class and at the same time multiple invocations of the macro do not result in the class redefinition ...