2

i have category schema and i want to insert new category if category name does not exist. I tried something but i could not any response.

category.model

var mongoose = require("mongoose");
var categorySchema = mongoose.Schema({
  name: {
    type: String,
    require: true
  },
  createdAt: {
    type: Date,
    default: () => {
      return new Date();
    }
  }
});

module.exports = mongoose.model("category", categorySchema);

category insert function

var Category = require("../models/category.model");
exports.create = (req, res) => {
  Category.find({ name: req.body.name }, (err, cat) => {
    if (cat.length > 0) {
     // i want to return exists message here
    } else {
      // i want to insert here if not exists
      var category = new Category();
      category.name = req.body.name;
      category.save(err => {
        if (err) {
          return new response(null, err).error500(res);
        }
        return new response(category, null).created(res);
      });
    }
  });
};
  • 1
    It should be `required: true`, not `require` – Mike K Jan 29 '20 at 09:12
  • Do you have any other error messages? The code looks almost right (see above comment). Also add an unique index on name (if you want to make sure you have only one category per name). – Antoine Jan 29 '20 at 09:25
  • Also sounds like `upsert` could answer your need of creating if not exists: https://stackoverflow.com/questions/7267102/how-do-i-update-upsert-a-document-in-mongoose – Antoine Jan 29 '20 at 09:26
  • Does this answer your question? [How do I update/upsert a document in Mongoose?](https://stackoverflow.com/questions/7267102/how-do-i-update-upsert-a-document-in-mongoose) – Antoine Jan 29 '20 at 09:27
  • @AntoineBolvy Thx, i've added unique index on name and i've taken response. – ERDEM NAYİR Jan 29 '20 at 09:29

1 Answers1

1

You can do it like this code below:

exports.create = async (req, res) => {
  try {
    let category = await Category.find({ name: req.body.name });

    if(category) {
      // return or do some stuff here
    }

    category = new Category(req.body);

    category = await category.save();

    return new response(category, null).created(res);

  } catch(ex) {
    console.log(ex.message);
    return new response(null, ex).error500(res);
  }
};

I hope it can help you.

Titus Sutio Fanpula
  • 3,467
  • 4
  • 14
  • 33
  • 2
    Careful on introducing promises where the initial code doesn't have some, you don't know how they will be handled, and you don't know if OP knows about them :) – Antoine Jan 29 '20 at 09:37