add data to mongoose database, wait for response in javascript

To add data to a Mongoose database, you can use the save() method on a Mongoose model instance. Here's an example:

index.tsx
const mongoose = require('mongoose');
const User = require('./models/user');

mongoose.connect('mongodb://localhost/mydatabase');

async function addUser(username, email, password) {
  const user = new User({
    username: username,
    email: email,
    password: password
  });

  try {
    const result = await user.save();
    console.log('User saved successfully:', result);
  } catch (error) {
    console.error('Error saving user:', error);
  }
}

addUser('johndoe', 'johndoe@example.com', 'pass123');
509 chars
22 lines

In this example, we define a function called addUser() that takes three parameters: username, email, and password. We create a new User instance with these values and then call the save() method on it.

Using async/await, we wait for the result of the save() method, which returns a promise. If the user is saved successfully, we log a success message with the saved user object. If there's an error, we log an error message with the error object.

Make sure to import the mongoose module and define a Mongoose schema for your data before trying to insert data into your database.

gistlibby LogSnag