Last active
December 17, 2015 22:29
-
-
Save tfanme/5682303 to your computer and use it in GitHub Desktop.
MongoDB Query 对象中 $or 的使用,判断 username 或 email 是否存在。
This file contains hidden or 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
| var userSignup = function (req, res) { | |
| var signup = req.body; | |
| // 用户对象 | |
| var muuser = { | |
| "username": signup.username, | |
| "password": signup.password, | |
| "firsttime": (new Date()).getTime(), | |
| "email": signup.email | |
| }; | |
| var result = { | |
| "success": false | |
| "description": "" | |
| }; | |
| db.collection('muusers', function(err, collection) { | |
| // 判断 username,或 email 是否存在 | |
| var query = { | |
| $or: [ | |
| {'username': signup.username}, | |
| {'email': signup.email} | |
| ] | |
| }; | |
| collection.findOne( , function(err, document) { | |
| assert.equal(null, err); | |
| if (document == null) { | |
| // 如果没有记录,则插入一条新的用户记录 | |
| collection.insert(muuser, {safe: true}, function(err, records){ | |
| console.log("Record added as " + records[0]._id); | |
| result.success = true; | |
| res.send(result); | |
| res.end(); | |
| }); | |
| } else { | |
| result.success = false; | |
| result.description = "username already exists"; | |
| res.send(result); | |
| res.end(); | |
| } | |
| }); | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment