MongoDB create a test database

I’m trying to persist data in my users’ collection that is inside a database that I created on MongoDB Atlas, the problem is every time I create a new user using my nodejs code and postman a new “test” database created with my users collection inside below is my sample code:
model:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  username: {
    type: String,
  },
  email: {
    type: String,
    unique: true,
    lowercase: true
  },
  password: {
    type: String,
  },
});

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

module.exports = User;

signup:

const User = require('../../models/userModel');
const bcrypt = require('bcryptjs');

const signup = async (req, res) => {
  try {
    const { username, email, password } = req.body;

    // Check if user exists
    const user = await User.exists({ email });
    if (user) {
      return res.status(409).send('This email is already taken!')
    }

    // Encrypt password
    const encryptedPassword = await bcrypt.hash( password, 10 );

    // create the user document
    const newUser = await User.create({
      username,
      email,
      password: encryptedPassword,
    })

    // create JWT token
    const token  = 'Some token data here'

    res.status(201).json({
      userData: {
        username: newUser.username,
        email: newUser.email,
        token,
      }
    })

  } catch (error) {
    return res.status(500).send('Something went wrong, please try again')
  }
};

module.exports = signup;

I attached a screenshot from MongoDB Atlas account that shows what I explained above:
Screenshot from 2023-02-02 07-53-16

2 Likes

Probably you need to specify database name in the connection string (...mongodb.net/your_db_name?retryWrites... )

2 Likes

Thank you @menteuse this is exactly what I needed to add, thank you buddy!

Not really menteuse if you are providing a true solution. B-)

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.