2017-12-27 382 views
0

我遇到了node + express路由问题。我在IDE webstorms中默认提供了一个路由模式。我不确定我是否配置了一切,因为我有这个错误。User.findByID不是函数

我可以做一个GET /用户和POST /用户正确的邮递员正确的结果。

路线/ users.js

const express = require('express'); 
const router = express.Router(); 
const _ = require('lodash'); 
const {ObjectID} = require('mongodb'); 

const {mongoose} = require('../db/mongoose') 
const {User} = require('../db/models/users') 
const {Project} = require('../db/models/projects') 
const {Dialog} = require('../db/models/dialogs') 

(...) 

router.get('/users/:userid', (req, res) => { 
    var id = req.params.userid.toString(); 

    if (!ObjectID.isValid(id)) { 
     return res.status(404).send(); 
    } 

    User.findByID(id).then((user) => { 
     if (!user) { 
      return res.status(404).send(); 
     } 

     res.send({user}); 
    }).catch(() => { 
     res.status(404).send(); 
    }); 
}); 

型号/ users.js

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

// todo refactor userschema with proper validators (view udemy course) 

const UserSchema = new Schema({ 
    email: {type: String, required: true}, 
    password: {type: String, required: true}, 
    name: {type: String}, 
    company: {type: String}, 
    phone: {type: String}, 
    projects: [{type: Schema.Types.ObjectId, ref: 'Project'}] 
}); 


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

module.exports = {User} 
+3

JavaScript是[区分大小写](https://docstore.mik.ua/orelly/webprog/jscript/ch02_02.htm)。尝试'findById'(强调最后一个字符)。 – Mikey

+1

'req.params.userid.toString();'这行也可能会导致问题,请注意'userid'中的小写字母' –

回答