Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.2 kB
1
Indexable
Never
// Connect to MongoDB
mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));

// Define a schema for the data
const mySchema = new mongoose.Schema({
  state1: String,
  state2: String,
  field3: String,
  field4: String
});

// Create a model based on the schema
const MyModel = mongoose.model('MyModel', mySchema);

// Serve the index.html file
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

// Handle the form submission
app.post('/submit', (req, res) => {
  // Create a new document based on the model
  const myData = new MyModel({
    state1: req.body.state1,
    state2: req.body.state2,
    field3: req.body.field3,
    field4: req.body.field4
  });

  // Save the document to the database
  myData.save((err) => {
    if (err) {
      console.error(err);
      res.status(500).send('Error saving data to MongoDB');
    } else {
      res.send('Data saved to MongoDB');
    }
  });
});

// Start the server
app.listen(3000, () => {
  console.log('Server listening on port 3000');
});