【问题标题】:mongo/express fetching user by id getting object = nullmongo/express 通过 id 获取用户对象 = null
【发布时间】:2018-12-18 12:42:56
【问题描述】:

所以我一直在尝试通过 ID 获取用户对象,使用 User.findById

postman 返回“user”:null,但我在请求中包含的 id 对象包含字段。

我的对象示例:

{ 
    "_id" : ObjectId("5b3cac4d18ca463e9c6dc574"), 
    "local" : {
        "email" : "test@test.lt", 
        "password" : "$2a$08$fxzlQnxn7mKpIdLYXg8edeet1CJoZaG.Ube2pNpLEGLQEXYuVA47e"
    }, 
    "__v" : NumberInt(0)
}

这是我的代码:

用户.js

const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

const { Schema } = mongoose;
const userSchema = new Schema({
  method: {
    type: String,
    enum: ['local', 'google', 'facebook'],
    required: true
  },
  local: {
    email: {
      type: String,
      lowercase: true
    },
    password: {
      type: String
    }
  },
  google: {
    id: {
      type: String
    },
    email: {
      type: String,
      lowercase: true
    }
  },
  facebook: {
    id: {
      type: String
    },
    email: {
      type: String,
      lowercase: true
    }
  }
});

路由/users.js

const express = require('express');
const router = require('express-promise-router')();
const passport = require('passport');
const router1 = express.Router();
require('../passport');

const { validateBody, schemas } = require('../helpers/routeHelpers');
const UsersController = require('../controllers/users');

const passportSignIn = passport.authenticate('local', { session: false });
const passportJWT = passport.authenticate('jwt', { session: false });

router.route('/signup')
  .post(validateBody(schemas.authSchema), UsersController.signUp);


router.route('/signin')
  .post(validateBody(schemas.authSchema), passportSignIn, UsersController.signIn);

router.route('/get/:id')
  .get(UsersController.getUser);


router.route('/secret')
  .get(passportJWT, UsersController.secret);

控制器/用户

module.exports = router;
const JWT = require('jsonwebtoken');
const User = require('../models/user');
const { JWT_SECRET } = require('../configuration');

const signToken = (user) => {
  return JWT.sign({
    iss: 'CodeWorkr',
    sub: user.id,
    iat: new Date().getTime(), // current time
    exp: new Date().setDate(new Date().getDate() + 1) // current time + 1 day ahead
  }, JWT_SECRET);
};

module.exports = {
  signUp: async (req, res) => {
    const { email, password } = req.value.body;

    // Check if there is a user with the same email
    const foundUser = await User.findOne({ 'local.email': email });
    if (foundUser) {
      return res.status(403).json({ error: 'Email is already in use' });
    }
    // Create a new user
    const newUser = new User({
      method: 'local',
      local: {
        email: email,
        password: password
      }
    });

    await newUser.save();

    // Generate the token
    const token = signToken(newUser);
    // Respond with token
    return res.status(200).json({ token });
  },
  signIn: async (req, res) => {
    // Generate token
    const token = signToken(req.user);
    res.status(200).json({ token });
  }, 
  getUser: async (req, res) => {
    User.findById(req.params.id)
      .then((user) => {
        res.status(200).json({ user });
        console.log('test');
      });
  },

  secret: async (req, res) => {
    console.log('I managed to get here!');
    res.json({ secret: 'resource' });
  }
};

我不知道,我的对象坏了怎么办?我需要深度克隆它吗?或者使用不同的功能,在此先感谢

【问题讨论】:

    标签: javascript node.js mongodb express


    【解决方案1】:

    您必须在 mongose 中定义模型(在您的 User.js 中)

    mongoose.model('User', userSchema);
    

    然后当你想查询时......

    const mongoose = require('mongoose');
    const User = mongoose.model('User');
    

    我认为这是你的问题,试一试。

    【讨论】:

    • 我确实在我的模型文件中导出了我的用户模式,只是没有写那个以节省时间 // 创建一个模型 const User = mongoose.model('user', userSchema); // 导出模型 module.exports = User;试过包括猫鼬,但没有用
    • 如果你调试用户(在那个文件中你正在运行查询)你会得到什么?另外,如果你调试用户(查询结果),你会得到什么
    • debu 用户你做什么?如果我从模式 const User = require('../models/user') 导入控制台日志用户,我会得到一堆字段,当我尝试在用户上使用 findbyid 时,我只会得到对象 null,如果我使用它也是一样的const mongoose = require('mongoose'); const user1 = mongoose.model('user');输出是一样的
    • 启用猫鼬日志并检查查询是否正确完成(将它们添加到问题中)。检查是否设置了 req.params.id。
    • mongoose log: Mongoose: users.findOne({ _id: ObjectId("5b3cac4d18ca463e9c6dc574") }, { fields: {} (也许这是问题字段为空?) }) (node:12144 ) [DEP0079] DeprecationWarning:不推荐使用通过 .inspect() 对对象的自定义检查功能 |我确实得到了 req.params.id 只是控制台记录了它
    猜你喜欢
    • 2021-03-20
    • 2011-09-03
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多