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?
Model.create()is a shortcut for saving one or more documents to the database.
MyModel.create(docs)doesnew 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
.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With