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

121
Visualizações
MongoDB print only one value of a collection. JavaScript

I'm having a problem with MongoDB console.logging only one data of a collection. I've already searched like infinite topics about this, but none of them does exactly what I want. I want to get one number data from my mongoose database. (I'm creating a discord.js bot) This is what the database looks like:

_id: 61bb8dc5a23c9a077066abf0
user: "soki#2400"
userId: "466270219132731392"
amount: 16
__v: 0

and I want to console.log() the value of amount.

This is my code now:

console.log(giftsSchema.find({"_id": 0},{"user": msg.author.tag},{"userId": msg.author.id}).amount);

So what I want it to print is:

16

But it prints

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

0

I think you mean to search on two fields user and userId. You should use this:

giftsSchema.findOne(
    {"user": msg.author.tag, "userId": msg.author.id}, // query
    function (err, user) { 
       console.log(user.amount); 
    });

If you want to use projection so that only the amount field is returned, then supply a second param with the fields you want 1 and don't want 0.

giftsSchema.findOne(
    {"user": msg.author.tag, "userId": msg.author.id}, // query
    {_id: 0, amount: 1}, // projection
    function (err, user) { 
        console.log(user.amount);
    });

In your example you are providing 3 parameters {"_id": 0}, {"user": msg.author.tag}, and {"userId": msg.author.id}. With find() the first param is the query/filter. So in your code you are querying for all records where _id = 0 and I don't think you want that. The second param is for projection, and you provided an invalid object for that, projection values should only be 1 or 0 like your first param. Third param is for options, and doesn't come into play here.

You want to query on multiple fields by having them in single object like this { field1 : value1, field2 : value2 }. I also think you only want one result, so you should use findOne() instead so you only get a single object in return and not an array of objects.

Also, Mongoose is asynchronous. So you should make an async function and await for the result. Or you can provide a callback function as shown in my example. NOTE: I don't handle the err case in my example.

about 4 years ago · Juan Pablo Isaza Relatório

0

.find() method will return a Promise. You should first wait for that Promise to resolve before logging the result. Try doing it this way:

const someFunction = async () => {
  let result = await giftsSchema.find({
    "user": msg.author.tag, "userId": msg.author.id
  }, {
    _id: 0, amount: 1
  });
  
  console.log('Result: ', result.amount);
}
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