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

<pre><code>var listitemSchema = new mongoose.Schema({
   name: String,
   rank: Number
}); 
</code></pre>

<p>...which exist inside a user:</p>

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

<p>...based on whether the user already has the name within his/her list. I was looking into <code>$addtoset</code> but can't really figure out how to put conditions when dealing with an object. The <a href="http://mongoosejs.com/docs/api.html#types_array_MongooseArray.addToSet" rel="nofollow">docs</a> 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:</p>

<pre><code>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");
         }
    });
});
</code></pre>

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