【问题标题】:mongoose is giving error invalid type on findById猫鼬在 findById 上给出错误无效类型
【发布时间】:2020-11-19 18:26:21
【问题描述】:

我是 node js 的新手,我试图用 mongoose 从 Mongo db 获取用户,但它给了我错误。这是我在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);

正在创建用户,但是当我尝试使用 mongoose 通过 id 查找用户时,它给了我一些 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 });
    });
});

单击 db.User 总是将我带到 User 模式的定义,但它仍会转到 catch 块,即使此用户存在于我的数据库中。

【问题讨论】:

  • 尝试将'connections.user': { $in: users }更改为'connections.user': { '$in': 'users' }
  • 尝试转换 userId。 userId = mongoose.Types.ObjectId(userId)

标签: node.js mongodb mongoose orm nosql


【解决方案1】:

使用那个 db.User.findById(ObjectId('5f20ec88d5cf2f2994bc42d4')), 如果您的 _id 是 object_id 而不是普通字符串,则必须使用 ObjectId

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-19
    • 2017-01-05
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    相关资源
    最近更新 更多