Home > Back-end >  How do i get my mongo schema to export into a file then use it to insert data?
How do i get my mongo schema to export into a file then use it to insert data?

Time:12-13

I am having troubles being able to insert data into my collection, im not even sure im doing it correctly so i apologize for the vauge request but maybe my code will help you see what my intention is. The gist of it is im trying to make a seperate 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,
)

CodePudding user response:

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

CodePudding user response:

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 reference. https://blog.logrocket.com/mern-stack-tutorial/

  • Related