0
votes

I am facing below issue while working on MEAN stack

TypeError: Message.find is not a function
at C:\Users\14379\Appchat\server\app.js:19:13
at Layer.handle [as handle_request]
(C:\Users\14379\Appchat\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\14379\Appchat\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\14379\Appchat\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\14379\Appchat\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\14379\Appchat\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\14379\Appchat\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\14379\Appchat\node_modules\express\lib\router\index.js:275:10)
at SendStream.error (C:\Users\14379\Appchat\node_modules\serve-static\index.js:121:7)
at SendStream.emit (events.js:315:20) at SendStream.error (C:\Users\14379\Appchat\node_modules\send\index.js:270:17)

app.js file is as shown below:

app.use(bodyParser.json())
app.use(express.static(path.join(__dirname, '../dist')))
const message = require('./models/message')
app.get('/api/chat', (req, res) => {
    Message.find(  ).then(rec => {
        if(rec) {
            console.log("Yo");
            res.send(rec)
            
        } else {
            console.log("Successful !!!");
            res.send([])
    // res.json({
    //     message:"hellu",
         }
        })
    
})
app.post('/api/chat', (req, res) => {
  const newMessage = new Message({
      _id: mongoose.Types.ObjectId(),
      message: req.body.message,
      user: 'user'
    })
    newMessage.save().then(rec => {
        if(rec) {
            res.send(rec)
        } else {
            res.send([])
        }
    })
})
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, '../dist/index.html'))
})
app.listen(3000, () => console.log('Listening on port 3000....'))



1
Replace your Message variable to message. You imported with a different names and using with a different names. - Prathamesh More
Thanks Prathamesh...even i figured it out...but was struck on this for entire day - Deep

1 Answers

0
votes

The error lies in these 3 lines:

const message = require('./models/message')
app.get('/api/chat', (req, res) => {
    Message.find(  ).then(rec => {

Had forgot to capitalize message..fixed the issue by rewiting:

const Message = require('./models/message')
app.get('/api/chat', (req, res) => {
    Message.find(  ).then(rec => {