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

标签 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 is not a function

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

当我期待与定义的模式类似的输出时,我得到一个查询,即使邮件存在,它也不包含任何信息

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 中结构化的集合)

最佳答案

缺少一个括号:

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;
}

关于javascript - 使用 .find() 的 Mongoose 静态函数返回查询,并且静态函数无法识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53222859/

相关文章:

javascript - 在 app.use 中传递参数(NODE.JS)

JSON Stringify 函数返回相等,但 chai 的 equal 函数返回不相等

javascript - _id 未定义,即使它就在 console.log(object) 中

javascript - 在表格中追加数组?

javascript - Dojo lang.replace - 如何提供默认值,而不是 'undefined' ?

node.js - Stripe webhook 测试错误 302

c# - 如何使用 MongoDB 的官方 C# 驱动程序检索所有嵌入式文档值?

javascript - 检查列中的所有复选框

javascript - 如何让 jQuery scrollTo 插件在 Facebook 中运行

mongodb - 如何导入go的mongo-driver bson