I don't understand how to use the findOrCreate method with mongoose I don't understand how to use the findOrCreate method with mongoose mongoose mongoose

I don't understand how to use the findOrCreate method with mongoose


In your cap.controller.js there are many errors. Firstly why the foc method is outside the cap_get one? And secondly you never call the foc method, why?

In your case you want to check whether a Cap with a title given by the params exists and if this is not the case create and it.

You can simply achieve that like that:

exports.cap_get = function (req, res, next) {  let capTitle = req.params.param1;  Cap.findOrCreate({ title: capTitle }, function(err, cap) {    if (err) return next(err);    console.log(capTitle + ' has been created !');    res.status(200).json({ title: capTitle });  });};

The cap_get is just an express callback with its (req, res, next) signature, and the findOrCreate first parameter is the primary key, so here if no caps exist with this key (the title) it'll create it else it'll return the document.

You'll have to ensure that the cap's title is unique to avoid potential issues:

let CapSchema = new Schema ({  title: {type: String, unique: true},  list: {type: Array}});