javascript - mongo/express 通过 id 获取用户获取对象 = null

标签 javascript node.js mongodb express

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

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

路由/user.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);

Controller /用户

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

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

最佳答案

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

mongoose.model('User', userSchema);

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

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

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

关于javascript - mongo/express 通过 id 获取用户获取对象 = null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51269131/

相关文章:

mongodb - 如何在聚合管道中执行 $match 阶段时添加限制

javascript - 正则表达式将字符串计数与通配符匹配

javascript - 使用 javascript 确定 ip 在 chrome 中有效,在 firefox 或 ie 中无效

php - 从远程服务器执行 php 中的 Node 脚本

javascript - TypeScript - 导入外部 npm 模块会导致 tsc 的输出文件夹发生更改

mongodb - MongoDB 中未启用 x.509 身份验证

javascript - 在不改变div位置的情况下替换css动画

javascript - React native - 从另一个组件调用函数关闭模式给出 `undefined is not an object`

node.js - ExpressJs 服务多个静态文件夹不工作

java - 使用 Morphia 和 Mongodb 持久化和检索 map map