mongodb mongoose忽略来自查询的当前用户

我正在编辑我的网站的编辑用户configuration文件页面。 当用户编辑他们的用户名并按保存,我想先检查,看看是否有其他用户首先有这个用户名。

User.findOne({'username' : newUsername }, function(err, user){ if (!user){ //no user exists with this name //code for changing current user's name to newUsername } else { //a user exists with this name //code for returning to the edit page, and displaying error message to user } }); 

问题是当我离开用户名相同(并编辑一个不同的值,如电子邮件)。 当它查询用户名时,它在mongodb上拉我的文档,因此它不会改变任何东西(因为用户存在!)。 我怎样才能把一个特定的文件完全从查询中删除?

如果我理解正确,你想抽象你的方法,以便它可以用来更改任何configuration文件属性,而不仅仅是用户名?

你可以做的是根据用户正在改变的字段dynamic地创build查询地图。

例如,如果您的用户想要更改他们的电子邮件字段:

(req.query.type ==什么字段用户试图改变)

(req.query.value ==用户试图改变的字段的值)

 var query = {}; switch(req.query.type) // Type is username, email, any profile field { case 'username': query['username'] = req.query.value // value of the profile field break; case 'email': query['email] = req.query.value break; default: break; } User.findOne(query, function(err, user) { // Query will differ depending on inputs if (!user) { //no user exists with the type //code for changing current user's info } else { //a user exists with this name //code for returning to the edit page, and displaying error message to user } });