3

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?

Alwaysblue
  • 9,948
  • 38
  • 121
  • 210
  • 2
    Possible duplicate of [mongoose save vs insert vs create](https://stackoverflow.com/questions/38290684/mongoose-save-vs-insert-vs-create) – Anurag Awasthi Oct 18 '18 at 10:52

3 Answers3

15

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

You Nguyen
  • 9,961
  • 4
  • 26
  • 52
  • Were you able to make sense of this? `newlyCreated.author.id = req.user._id; newlyCreated.author.username = req.user.username; newlyCreated.save();` Because In the above if I did something like this ` playground.create({` then why did we do something like this `newlyCreated.save()`? Also thanks a lot for asking :) – Alwaysblue Oct 18 '18 at 11:30
2

.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

tnvr_98
  • 121
  • 1
  • 2
0

Read Constructing Documents section. .save() and .create() are just different ways to add documents to the collection.

https://mongoosejs.com/docs/models.html

const Tank = mongoose.model('Tank', yourSchema);

const small = new Tank({ size: 'small' });
small.save(function (err) {
  if (err) return handleError(err);
  // saved!
});

// or

Tank.create({ size: 'small' }, function (err, small) {
  if (err) return handleError(err);
  // saved!
});

// or, for inserting large batches of documents
Tank.insertMany([{ size: 'small' }], function(err) {

});
Max Vhanamane
  • 163
  • 2
  • 7
  • I donot remember where i learned this but , .save() directly saves the document into the DB without verifying the schema whereas .create will first check if the data to be saved is valid according to schema and then only it will trigger .save() method . – tnvr_98 Dec 15 '22 at 20:21
  • You are saying .save() skips the schema verification I don't think that is true. Because most of the time I use .save() to save the document in the DB. and whenever I try to add something that is against my schema I do get errors. The .save() is an instance method of the model, while the .create() is called directly from the Model as a method call, being static in nature, and takes the object as a first parameter. – Max Vhanamane Dec 16 '22 at 03:58