Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose difference between .create and .save

I did a bootcamp on udemy long back on Express and Mongoose where suppose we want to add new field in data, we did something like this

var playground = require("../models/playground.js");

route.post("/", middleware.isLoggedIn,function (req, res) {

  var name =  req.body.name;
  var image =  req.body.image;
  var description = req.body.description;
  var price = req.body.price;

  playground.create({
    name: name,
    image:image,
    description: description,
    price: price
  }, function(error, newlyCreated){
    if(error) {
      console.log(error)
    }
    else {
      newlyCreated.author.id = req.user._id;
      newlyCreated.author.username = req.user.username;
      newlyCreated.save();
     res.redirect("/playground");
    }
  })
});

Now, it's been about more than year and I am unable to comprehend what I am doing here (should have added some comments) but I do see we are using something like this playground.create({

and then there is this here which I completely unable to comprehend

          newlyCreated.author.id = req.user._id;
          newlyCreated.author.username = req.user.username;
          newlyCreated.save();

This isn't a primary question but what will newlyCreated.save(); will do? I mean it would probably save the data we are getting from the front end but how will it work?

Moving on to the primary question, I was again following a tutorial where the instructor did something as simple as this to save data

 let author = new Author({  
     name: args.name, 
     age: args.age
       })
 author.save()

So what is in general difference between .create and .save?

like image 376
iRohitBhatia Avatar asked Nov 26 '25 23:11

iRohitBhatia


2 Answers

Model.create() is a shortcut for saving one or more documents to the database.

MyModel.create(docs) does new MyModel(doc).save() for every doc in docs.

This function triggers the following middleware.

  • save()

Reference:https://mongoosejs.com/docs/api.html#model_Model.create

like image 104
You Nguyen Avatar answered Nov 28 '25 13:11

You Nguyen


.save() and .create() both does the same work. The important difference is that .save() bypasses schema validation but .create() checks if the data conforms the schema and then it will trigger the .save() method internally

like image 44
tnvr_98 Avatar answered Nov 28 '25 14:11

tnvr_98