Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

206
Visualizações
What's the point of using save() in Mongoose?

I'm learning MongoDB and Mongoose, and I've watched instructors advise to use the save() function to save the changes made to the database.

But I'm still making changes successfully without using save(). I've made two functions to add a document to the database, one with using save() and the second one without using save(), and they all did the same job.

So, what's the point of using it then?

NOTE: I've hided my connect string

My Code:

const express = require('express');
const mongoose = require('mongoose');

//-- Connect to Database --//:
mongoose.connect();

// make Schema & model:
const Person = mongoose.model('Person', new mongoose.Schema({
    name: String,
    age: Number
}));

//-- Interact with Database --//:
async function run1 () {
    const person = await Person.create({name: 'John', age: 25});
    await person.save();
    console.log(person);
}

async function run2 () {
    const person = await Person.create({name: 'Sally', age: 40});
    console.log(person);
}

run1();
run2();

Terminal output:

PS C:\Users\user\OneDrive\Desktop\Folders\Programming\Web Development\Web Development Projects\Database-Practice> node server
{
  name: 'Sally',
  age: 40,
  _id: new ObjectId("61d20d852b1e59a6b21149b1"),  __v: 0
}
{
  name: 'John',
  age: 25,
  _id: new ObjectId("61d20d852b1e59a6b21149b0"),  __v: 0
}

Picture of my Database after running my code:

enter image description here

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Mongoose models have a create() function that is often used to create new documents.

const User = mongoose.model('User', mongoose.Schema({
email: String
}));

const doc = await User.create({ email: 'bill@microsoft.com' });
doc.email; // 'bill@microsoft.com'

The create() function is a thin wrapper around the save() function. The above create() call is equivalent to:

 const doc = new User({ email: 'bill@microsoft.com' });
 await doc.save();

The most common reason for using create() is that you can conveniently save() multiple documents with a single function call by passing an array of objects:

 const User = mongoose.model('User', mongoose.Schema({
 email: String
 }));

 const docs = await User.create([
 { email: 'sergey@google.com' },
 { email: 'bill@microsoft.com' }
 ]);
 docs[0] instanceof User; // true
 docs[0].email; // 'sergey@google.com'
 docs[1].email; // 'bill@microsoft.com'
about 4 years ago · Juan Pablo Isaza Relatório

0

From the docs:

Shortcut for saving one or more documents to the database. MyModel.create(docs) does new MyModel(doc).save() for every doc in docs.

Looking at what you've got, let me point out:

async function run1 () {
    const person = await Person.create({name: 'John', age: 25});
    await person.save(); // unnecessary 2nd call here
    console.log(person);
}

Behind the scenes your code will run like:

async function run1 () {
    const person = await new Person({name: 'John', age: 25}).save();
    await person.save(); // saving twice basically
    console.log(person);
}

What you can do is (this is preferred by most):

async function run1 () {
    const person = new Person({name: 'John', age: 25});
    await person.save();
}

The reason is that doing so gives you more control when saving your document. For example, you can pass the person object to any function and save it inside that function instead without requiring the model to wherever that function exists in your codebase.

async function run1 () {
    const person = new Person({name: 'John', age: 25});
    await doSth(person); // showing possibility, not a recommendation
}

// This function can exist anywhere, does not have to be in the same file
async doSth(person){
  // do some logging maybe
  // change some properties of the person maybe
  // slug-ify the persons name maybe
  await person.save();
}

Doing this allows you to have a better separation of concern. Other than that, both will produce the same behavior and is pretty much a matter of preference. But the current standard in the community goes with the .save() method.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda