2017-12-27 1092 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'中的小寫字母' –

回答