节点JS-检查mongo DB中是否存在字段

Bol*_*boa 2 mongoose mongodb node.js

我不确定我是否走在正确的轨道上,但这就是我所拥有的......

router.post('/login', function(request, response) {
    User.find({ 'username': request.body.email,'email':request.body.pwd }, function(err, user) {
    //do not know what to add here
Run Code Online (Sandbox Code Playgroud)

POST从两个输入字段中获取数据,然后使用find命令检查我的mongo数据库中是否已存在此字段.

User是我创建的模型架构.它看起来如此......

var Schema = new mongoose.Schema({
    email    : String,
    password : String,
    display  : String   
});
var User = mongoose.model('User', Schema);
Run Code Online (Sandbox Code Playgroud)

我想我在正确的轨道上,但我不确定在find命令中添加什么.如果两个字段一起存在,我想做一件事,如果不是我想抛出错误,我该怎么做?

und*_*ned 6

我建议使用findOneover find,因为如果它存在,它将返回单个文档,否则null.

router.post('/login', function(request, response) {
   // use `findOne` rather than `find`
   User.findOne({ 
    'username': request.body.email,
    'email':request.body.pwd }, function(err, user) {
      // hanlde err..
      if (user) {
        // user exists 
      } else {
        // user does not exist
      }
   })
 })
Run Code Online (Sandbox Code Playgroud)