Jon
Jon

Reputation: 161

Create new document if there is not document with same name mongoose

var userSchema = mongoose.Schema({
    username: { type: String},
    email: String,
    password: String,
    tasks: [String]
});

I want to create a new user document only if there is no another user with the same name. What the best way to do that? this is my implementation currently :

router.post('/', async function(req, res, next) {
use  let user= await User.findOne({ name: req.body.name})
        if (user) {
            if (req.body.name == user.name) {
                // return new Error("User exists!"));
        } 
    User.create(req.body, function (err, newuser) {
        if (err) {
            console.log(err);
            return next(err);
        }
        res.json(newuser);
    });

    }

Another question about mongoDB collections: Should I open new collection ( and schema) for 'task' property? It has only 1 field - the task itself in type string.

Upvotes: 1

Views: 114

Answers (1)

Hafez
Hafez

Reputation: 1440

Your current implementation is the way to go, you find the user, if none is found, you create a new one.

I refactored your code a little bit, here's how it would look like:

router.post('/', async function (req, res, next) {
  try {
    const user = await User.findOne({ name: req.body.name });
    if (user) {
      return res.json(user);
    }

    const newUser = await User.create(req.body);

    return res.json(newUser);
  } catch (err) {
    console.log(err);
    return next(err);
  }
});

As to your second question, if you're sure that the task will always be a simple string and you won't need more data in there, it's better to keep it embedded within the document.

It's likely that you'll need to extend functionalities for tasks, and add more data such as a status, deadline, maybe subtasks, in which case it's better to separate it in a different collection.

This series of articles is probably a good place to quickly learn a rule of thumb on how to design your schemas.

Upvotes: 1

Related Questions