Last active
December 24, 2015 21:19
-
-
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...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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