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

364
Visualizações
How to save in Mongoose with await?

The below code works, but I would like to only use async/await, so my question is ´: How can I turn

cat.save().then(() => console.log('Saved in db'));

into using await instead?

The reason I have mongoose.connection.once() is to only send commands when MongoDB is connected. if this could use await as well, then it would be really great =)

import mongoose from 'mongoose';
import { connectDb } from './modules/connectDb';
const { Schema } = mongoose;
const catSchema = new Schema({ name: String });
    
(async () => {
  connectDb('testDB');

  mongoose.connection.once('open', () => {
    console.log('MongoDB is connected');

    mongoose.connection.db.listCollections().toArray(function (err, names) {
      console.log(names);
    });

    const catModel = mongoose.model('testColl', catSchema);

    const cat = new catModel({ name: 'Zildjian' });
    cat.save().then(() => console.log('Saved in db'));
  });
})();

connectDb.ts

import mongoose from 'mongoose';
import { strict as assert } from 'assert';
import { readToml } from './readToml';

const db = readToml('./config/database.toml');

export function connectDb(
  database: string = db.database,
  uri: string = db.uri,
  username: string = db.username,
  password: string = db.password,
) {
  assert(typeof uri === 'string');
  assert(typeof database === 'string');
  assert(typeof username === 'string');
  assert(typeof password === 'string');

  const URI = `mongodb+srv://${username}:${password}@${uri}/${database}?retryWrites=true&w=majority`;

  try {
    mongoose.connect(URI);
  } catch (err) {
    console.error(err);
  }
}
almost 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Try below code and make sure the function contains await keyword should always async function (async keyword should be used before function name). But in your case callback function already defined as async function.

Just change the saving part alone to below, you are good to go.

try {
    const catModel = mongoose.model('testColl', catSchema);
    const cat = new catModel({ name: 'Zildjian' });
    const response = await cat.save(); // if error while saving, catch will get executed
    console.log(response); // saved record
    // return success response 
} catch (err) {
    console.log('err' + err);
    // return error response
}
almost 4 years ago · Santiago Trujillo Relatório

0

First you need to make connectDB async and then git rid of mongoose.connection.once() as you otherwise would need all your Mongoose code to be in there.

main().catch((err) => console.log(err));

async function main() {
  await connectDb('testDB');

  const catSchema = new mongoose.Schema({ name: String });
  const catDocument = mongoose.model('testColl', catSchema);

  const catObj = new catDocument({ name: 'Zildjian' });
  await catObj.save();
}

connectDB

import mongoose from 'mongoose';
import { strict as assert } from 'assert';
import { readToml } from './readToml';

const db = readToml('./config/database.toml');

export async function connectDb(
  database: string = db.database,
  uri: string = db.uri,
  username: string = db.username,
  password: string = db.password,
) {
  assert(typeof uri === 'string');
  assert(typeof database === 'string');
  assert(typeof username === 'string');
  assert(typeof password === 'string');

  const URI = `mongodb+srv://${username}:${password}@${uri}/${database}?retryWrites=true&w=majority`;

  const options = {
    bufferCommands: false,
    autoCreate: false,
  };

  try {
    await mongoose.connect(URI, options);
  } catch (err: any) {
    throw err.message;
  }
}
almost 4 years ago · Santiago Trujillo Relatório

0

In order to use await you have to provide a promise to await for. cat.save() returns a promise, so this should work. Nevertheless you can also only use await in async function, so you should also declare the callback function for the open event as async:

(async () => {
  connectDb('testDB');

  mongoose.connection.once('open', async () => {
    console.log('MongoDB is connected');

    mongoose.connection.db.listCollections().toArray(function (err, names) {
      console.log(names);
    });

    const catModel = mongoose.model('testColl', catSchema);

    const cat = new catModel({ name: 'Zildjian' });
    await cat.save();
    console.log('Saved in db');
  });
})();
almost 4 years ago · Santiago Trujillo 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