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

165
Visualizações
How to use updateOne in Mongodb using NodeJS

Below is my code to update a website field in Mongodb using NodeJS, instead of updating however it adds a new field to my database.

let { ObjectId } = require('mongodb');

  async get(id) {
    if (!id) throw 'You must provide an id to search for';

    const restaurantsCollection = await restaurants();
    const res = await restaurantsCollection.findOne({ _id: id });
    if (res === null) throw 'No dog with that id';
    res._id = res._id.toString().replace(/ObjectId\("(.*)"\)/, "$1")
    return res;
  }

async rename(id, newWebsite) {
    if (!id) throw 'You must provide an id to search for';

    if (!newWebsite) throw 'You must provide a name for the restaurant';

    let newid = ObjectId(id);
  
    const restaurantsCollection = await restaurants();
    const updatedInfo = await restaurantsCollection.updateOne(
      { _id: newid },
      { $set: {website:newWebsite} }
    );
    if (updatedInfo.modifiedCount === 0) {
      throw 'could not update restaurant successfully';
    } 
    
    return await this.get(newid);
  } 
};

Below is the output I get:

{
  _id: new ObjectId("6157825a4dcae5beb8f759bf"),
  name: 'Hey',
  location: 'New York City, New York',
  phoneNumber: '123-456-7890',
  website: 'http://www.hey.com',
  priceRange: '$$$$',
  cuisines: [ 'Cuban', 'Italian' ],
  overallRating: 3,
  serviceOptions: { dineIn: true, takeOut: true, delivery: false },
  newWebsite: 'http://www.hi.com'
}

Instead of the website being replaced from hey.com to hi.com it just adds a new field, what am I doing wrong?

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

0

Instead of using { $set: {website:newWebsite} }

It should just be {website:newWebsite}

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