简体   繁体   English

mongoose 在 findById 上给出错误无效类型

[英]mongoose is giving error invalid type on findById

I am new to node js, I was trying to get user from Mongo db with mongoose but it is giving me error.我是节点 js 的新手,我试图使用 mongoose 从 Mongo db 获取用户,但它给了我错误。 THis is my UserScheme in db.js :这是我在 db.js 中的db.js

const config = require('config');

const mongoose = require('mongoose');
const Schema   = mongoose.Schema;

mongoose.connect(config.get('mongo.uri'));
mongoose.set('debug', config.get('app.verbose') === true);
mongoose.set('useFindAndModify', false);

const UserSchema = new Schema({
       phone             : String,
       shortPhone        : String,
       password          : String,
       averageRating     : Number,
       profile           : {
               email        : String,
               mainlyHereFor: String,
               enabledVideoResume: {type: Boolean, default: false},
               seekingOpportunityType: String,
               fullName     : String,
               username     : String,
               address      : {
                       city   : {type: String, default: 'Unknown'},
                       state  : String,
                       country: String,
                       zip    : String
               },
      }
}

exports.User = mongoose.model('User', UserSchema);

The user is being created, but when I am trying to find the user by id with mongoose it is giving me some invalid type error:正在创建用户,但是当我尝试通过 ID 使用 mongoose 查找用户时,它给了我一些invalid type错误:

const express = require('express');
const db = require('../db');

router.get('/search', (req, res) => {
  db.User.findById('5f20ec88d5cf2f2994bc42d4') // req.user.id)
    .then((user) => {
      let connsFilter = user.connections.filter((conn) => conn.relationship == 'connected');
      const users = connsFilter.map((conn) => conn.user);

      let query = {
        'connections.user': { $in: users }
      };

      return db.User.find(query)
        .select('-contacts')
        .populate({ path: 'jobs', match: { spam: false } });
    })
    .then((result) => {
      res.json(result);
    })
    .catch((err) => {
      res.status(400).json({ status: 'bad', error: err });
    });
});

Clicking on db.User always takes me to the definition of User schema but it still goes to the catch block, even if this user exists in my database.单击 db.User 总是将我带到 User 模式的定义,但它仍会转到 catch 块,即使该用户存在于我的数据库中。

use that db.User.findById(ObjectId('5f20ec88d5cf2f2994bc42d4')), you have to use ObjectId if ur _id is object_id instead of normal string使用那个 db.User.findById(ObjectId('5f20ec88d5cf2f2994bc42d4')),如果你的 _id 是 object_id 而不是普通字符串,则必须使用 ObjectId

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM