【问题标题】:Mongoose static function that uses .find() returns query and static function is not a recognized使用 .find() 的 Mongoose 静态函数返回查询并且静态函数无法识别
【发布时间】:2021-10-04 11:02:42
【问题描述】:

所以我已经声明了一个模式并为其提供了一个静态函数,通过电子邮件在下面的文件中搜索用户:

./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 }

所以她我面临 2 个问题,

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

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    缺少一个括号:

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

    【讨论】:

    • 我的错,这是一个复制过去的错误,我纠正了它,但它不是我的问题的根源,因为否则我会收到其他错误消息。但你是对的,我没有注意复制过去的错误
    • @El.KIbrahim 我编辑了我的答案,你可以在回调函数中得到 find 的结果。
    • 我看到你在那里做了什么,但显然变量数据在回调中调用时不会更新,而且我不明白的是结果 ifself 不是查询来自哪里,通常返回的输出应该是遵循前面定义的模式的数组。我也认为回调是不必要的,我会试着抓住它,但为了简单起见,我只是做了一个返回
    【解决方案2】:

    在您的模型中

    UserSchema.statics.findByEmail = function (email) {
        return new Promise((resolve, reject) => {
            return this.findOne({ email: email }).exec(function (err, user) {
                if (err) reject(err)
                resolve(user);
            });
        });
    }

    【讨论】:

      猜你喜欢
      • 2014-04-27
      • 1970-01-01
      • 1970-01-01
      • 2017-08-14
      • 2015-08-17
      • 1970-01-01
      • 1970-01-01
      • 2021-08-29
      • 1970-01-01
      相关资源
      最近更新 更多