Skip to content

Instantly share code, notes, and snippets.

@maxlibin
Last active December 24, 2015 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxlibin/6864721 to your computer and use it in GitHub Desktop.
Save maxlibin/6864721 to your computer and use it in GitHub Desktop.
Node.js mongoose query if item exist in array,and insert and update if does not...
exports.user_post_emails = function(req, res){
var emails = [];
Mongoose_Collection.findOne({userId: req.user._id}, function(err, user){
if(!user){
emails[0] = req.body.emails;
new Mongoose_Collection({
emails: emails,
userId:req.user._id
}).save();
} else {
// the current length of the array..
Mongoose_Collection.findOne({userId: req.user._id}, function(err, user){
_length = user.emails.length;
function in_array(array, id) {
for(var i=0;i<array.length;i++) {
if(array[i][0].id === id) {
return true;
}
}
return false;
}
var result = in_array(user.emails, req.body.emails);
if(!result){
emails = user.emails;
emails[_length] = req.body.emails;
Mongoose_Collection.update({
userId: req.user._id
}, {
$set: {
emails: emails
}
}).exec();
}
});
}
})
res.render("user", {
username: req.user.username,
user: req.user
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment