'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?



Solution 1:[1]

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

Solution 2:[2]

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) {

});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 You Nguyen
Solution 2 Max Vhanamane