Home > other >  MongoDB print only one value of a collection. JavaScript
MongoDB print only one value of a collection. JavaScript

Time:12-17

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

CodePudding user response:

.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);
}

CodePudding user response:

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.

  • Related