使用.find()的Mongoose静态函数返回查询,并且无法识别静态函数

时间:2018-11-09 09:18:14

标签: javascript node.js mongodb mongoose

所以我已经声明了一个架构并为其提供了静态功能,该功能可以通过以下文件中的电子邮件搜索用户:

./ database.js

const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/investDB', { useNewUrlParser: true })

const Schema = mongoose.Schema

var UserSchema = new Schema({
  email: String,
  username: String,
  password: String,
  firstName: String,
  lastName: String
})

UserSchema.statics.findByEmail = function (email) {
      return this.find({email: email })
}

var User = mongoose.model('User', UserSchema)
module.exports = User

并被另一个文件调用

./ fonctions.js

var mongooseModel = require('./database')

function loginAlreadyExist(emailInput) {
  var onDataBase = new mongooseModel()
  return onDataBase.findByEmail(emailInput)
}

exports.loginAlreadyExist = loginAlreadyExist

使用静态功能后,出现以下错误

  

onDataBase.findByEmail不是函数

此后,我决定首先查看findByEmail返回的内容,因此在导出 ./ database.js 之前,我添加了console.log(User.findByEmail("a@a"))

当我期望输出类似于所定义的架构时,我得到了一个查询instade,即使该邮件存在,它也不包含任何信息

Query {
  _mongooseOptions: {},
  _transforms: [],
  mongooseCollection: 
   NativeCollection {
     collection: null,
     opts: 
      { bufferCommands: true,
        capped: false,
        '$wasForceClosed': undefined },
     name: 'users',
     collectionName: 'users',
     conn: 
      NativeConnection {
        base: [Object],

....
options: {},
  _conditions: { email: 'a@a' },
  _fields: undefined,
  _update: undefined,
  _path: undefined,
  _distinct: undefined,
  _collection: 
   NodeCollection {
     collection: 
      ....
     collectionName: 'users' },
  _traceFunction: undefined,
  '$useProjection': true }

所以她在两个问题面前,

1)为什么无法识别静态功能 2)为什么findByEmail输出不尊重架构(或mongodb中构造的集合)

1 个答案:

答案 0 :(得分:0)

缺少括号:

UserSchema.statics.findByEmail = function (email) {
    return this.find({email: email })
}

您还可以在find()的回调函数中获得查询结果:

UserSchema.statics.findByEmail = function (email) {
    let data;
    this.find({email: email }, function (err, result) {
        if (err) throw err;
        data = result;
    }
    return data;
}