skip to Main Content

I am having trouble being able to insert data into my collection, I’m not even sure I’m doing it correctly so I apologize for the vague request but maybe my code will help you see what my intention is. The gist of it is I’m trying to make a separate file for my schema/collection and then call it from another file and insert data and call other functions etc.

file1.js file:

require('dotenv').config()
 const User = require('./assets/js/data')

const bodyParser = require("body-parser");
const mongoose = require('mongoose');


mongoose.connect(process.env.url, { useNewUrlParser: true })
  .then(() => {
    console.log('Connected to MongoDB server');
  })



  // 1. Import the express module
const express = require('express');

// 2. Create an instance of the express application
const app = express();
app.set('views', './static/html');
app.set('view engine', 'ejs');
app.use(express.static('assets'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 3. Define the HTTP request handlers
app.get('/', (req, res) => {
  res.render('main')
});

app.get('/login', (req, res) => {
  res.render('login')
});

app.post('/login', (req, res) => {
  console.log(req.body.number);

  
  
  
})



app.listen(3000, (err) => {
  console.log("running server on port")
  if (err) {
    return console.log(err);
  }
})

data.js

const mongoose = require('mongoose');

const userData = new mongoose.Schema({
    phoneNumber: String,
})

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



module.exports(
    User,
)

2

Answers


  1. The Data.js is correct but the way your controller works is I think the issue. If you use "const User = require(‘./assets/js/data’)" you can use your selected variable User and then connect find, create, etc. you can use this as a reference. https://blog.logrocket.com/mern-stack-tutorial/

    Login or Signup to reply.
  2. This line has the error.

    // error
    module.exports(
        User,
    )
    

    module.exports is not a function.

    module.exports = User
    
    // or
    
    module.exports = { User }
    

    if you do the first one, then required should be like this,

     const User = require('./assets/js/data')
    

    otherwise

     const { User } = require('./assets/js/data')
    

    More about module.exports

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search