mongodb Mongoose FindOne返回查询和集合,而不是集合中的文档

wbrvyc0a  于 2023-01-04  发布在  Go
关注(0)|答案(2)|浏览(140)

我是NodeJS的新手,正在尝试为我的大学项目开发mongoose,我一直在尝试使用model. findOne()方法从集合中检索文档,但是,mongoose并没有从集合中返回文档,而是返回了查询和模型元数据。
在userModel.findOne()之前添加await只会导致mongoose的查询已执行错误。
用户架构

var mongoose = require('mongoose');

//Define Collection Schema
const userSchema = new mongoose.Schema({
    emailId:{
        type: String,
        required: true
    },

    userName:{
        type: String,
        required: true
    },

    password:{
        type: String,
        required: true
    },

    role:{
        type: String,
        required: true,
        default: "user"
    },
    
    playlist:[{
        type: String,
        type: mongoose.Schema.Types.ObjectId,
        ref: "vidmodel"
    }],

    likes:[{
        type: String,
        type: mongoose.Schema.Types.ObjectId,
        ref: "vidmodel"
    }],

    dislikes:[{
        type:  String,
        type: mongoose.Schema.Types.ObjectId,
        ref: "vidmodel"
    }]
})

userSchema.pre('save', function(next) {
    this.emailId=this.emailId.toLowerCase();
    next();
})

module.exports = mongoose.model('usermodel', userSchema)

功能

const userModel = require('./models/userModel')

app.post('/user/signup', upload.single(''), async(req,res)=>{
    try{
        const formData = req.body
        const email = formData.email
        const password = formData.password
        existingUser=userModel.findOne({emailId:email}, function(err, user){
            if(user){
                console.log("output of findOne",user)
            }
            if(err){
                console.log(err)
            }
        })
        if(existingUser){
            console.log(existingUser)
        }
    }
    catch(err){
        console.log(err)
    }
})

输出:

Query {
  _mongooseOptions: {},
  _transforms: [],
  _hooks: Kareem { _pres: Map(0) {}, _posts: Map(0) {} },
  _executionStack: null,
  mongooseCollection: Collection {
    collection: Collection { s: [Object] },
    Promise: [Function: Promise],
    modelName: 'usermodel',
    _closed: false,
    opts: {
      autoIndex: true,
      autoCreate: true,
      schemaUserProvidedOptions: {},
      capped: false,
      Promise: [Function: Promise],
      '$wasForceClosed': undefined
    },
    name: 'usermodels',
    collectionName: 'usermodels',
    conn: NativeConnection {
      base: [Mongoose],
      collections: [Object],
      models: [Object],
      config: {},
      replica: false,
      options: null,
      otherDbs: [],
      relatedDbs: {},
      states: [Object: null prototype],
      _readyState: 1,
      _closeCalled: undefined,
      _hasOpened: true,
      plugins: [],
      id: 0,
      _queue: [],
      _listening: false,
      _connectionString: 'mongodb://localhost/streambytes-dev',
      _connectionOptions: [Object],
      client: [MongoClient],
      '$initialConnection': [Promise],
      db: [Db],
      host: 'localhost',
      port: 27017,
      name: 'streambytes-dev'
    },
    queue: [],
    buffer: false,
    emitter: EventEmitter {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      [Symbol(kCapture)]: false
    }
  },
  model: Model { usermodel },
  schema: Schema {
    obj: {
      emailId: [Object],
      userName: [Object],
      password: [Object],
      role: [Object],
      playlist: [Array],
      likes: [Array],
      dislikes: [Array]
    },
    paths: {
      emailId: [SchemaString],
      userName: [SchemaString],
      password: [SchemaString],
      role: [SchemaString],
      playlist: [SchemaArray],
      likes: [SchemaArray],
      dislikes: [SchemaArray],
      _id: [ObjectId],
      __v: [SchemaNumber]
    },
    aliases: {},
    subpaths: {
      'playlist.$': [ObjectId],
      'likes.$': [ObjectId],
      'dislikes.$': [ObjectId]
    },
    virtuals: { id: [VirtualType] },
    singleNestedPaths: {},
    nested: {},
    inherits: {},
    callQueue: [],
    _indexes: [],
    methods: {},
    methodOptions: {},
    statics: {},
    tree: {
      emailId: [Object],
      userName: [Object],
      password: [Object],
      role: [Object],
      playlist: [Array],
      likes: [Array],
      dislikes: [Array],
      _id: [Object],
      __v: [Function: Number],
      id: [VirtualType]
    },
    query: {},
    childSchemas: [],
    plugins: [ [Object], [Object], [Object], [Object], [Object] ],
    '$id': 3,
    mapPaths: [],
    s: { hooks: [Kareem] },
    _userProvidedOptions: {},
    options: {
      typeKey: 'type',
      id: true,
      _id: true,
      validateBeforeSave: true,
      read: null,
      shardKey: null,
      discriminatorKey: '__t',
      autoIndex: null,
      minimize: true,
      optimisticConcurrency: false,
      versionKey: '__v',
      capped: false,
      bufferCommands: true,
      strictQuery: true,
      strict: true,
      pluralization: true
    },
    '$globalPluginsApplied': true
  },
  op: 'findOne',
  options: {},
  _conditions: { emailId: 'JCD@unatco.com' },
  _fields: undefined,
  _update: undefined,
  _path: undefined,
  _distinct: undefined,
  _collection: NodeCollection {
    collection: Collection {
      collection: [Collection],
      Promise: [Function: Promise],
      modelName: 'usermodel',
      _closed: false,
      opts: [Object],
      name: 'usermodels',
      collectionName: 'usermodels',
      conn: [NativeConnection],
      queue: [],
      buffer: false,
      emitter: [EventEmitter]
    },
    collectionName: 'usermodels'
  },
  _traceFunction: undefined,
  '$useProjection': true
}

我试过使用回调函数,但没有任何结果;试过问题中提到的代码,但只会将查询和模型元数据作为输出。在findOne之前使用async关键字只会导致查询已执行错误。我不知道这里的问题是什么。

xqk2d5yq

xqk2d5yq1#

尝试像这样使用async/wait:

app.post('/user/signup', upload.single(''), async(req,res)=>{
     try{
         const formData = req.body
         const email = formData.email
         const password = formData.password
         const user = await userModel.findOne({emailId: email}).exec();
             
             if(user){
                console.log("output of findOne", user)
              // your response logic
             } else {
               console.log("User does not existe") 
             // your response logic
             }
     }catch(err){
         console.log(err)
     });

您可以选择使用回调或异步/等待语法与try/catch,但不要混合在一起,因为回调将处理自己的错误,无论如何,如果可以的话,最好使用异步/等待,它更容易阅读。
你可以检查mongoose文档:https://mongoosejs.com/docs/api.html#model_Model-findOne

41zrol4v

41zrol4v2#

查询编写正确,但由于某种原因,VS代码拒绝识别为emailId字段提供值的email变量。即使该变量确实包含正确的值,但未将其传递给findOne()。只需昨天关闭系统,今天启动即可解决问题
虽然我还不清楚它为什么一直返回查询,但可能是由于无法找到文档而使它返回查询

相关问题