Home > Blockchain >  How do I get data from mongodb, manipulate it and print it
How do I get data from mongodb, manipulate it and print it

Time:09-22

I want to connect to MongoDB and query a collection based on the filter 'category'. From the results, I want to randomly select one of entries, concatenate with another string and print to console. I am a novice at this and can't figure out how to get the results of my query and randomly select one of the entries from the query results.

//Connecting To DB
  
const mongoose = require('mongoose');
//const { makeCard } = require('./utils/card');
const db = mongoose.connection;

const host = process.env.host;
console.log(host)
 
const dbupdate = {
    useNewUrlParser : true,
    useUnifiedTopology : true
};
mongoose.connect(host, dbupdate);

db.on('error', (err) => console.log('Error, DB not connected'));
db.on('connected', () => console.log('connected to mongo'));
db.on('disconnected', () => console.log('Mongo is disconnected'));
db.on('open', () => console.log('Connection Made!'));

const Schema= mongoose.Schema;

const cardSchema = new Schema({
    word: String,
    visual : String,
    category : String
});

const Card = mongoose.model('expressions', cardSchema );

--I want this function to return the results of the query, but it doesn't.
function getWords(ctgry ) {
    const result = Card.find({"category" : ctgry },(error,results) => {
        return results;
    });  
}; 

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min)   min); 
  };

  function getWord( ctgry ) {
    const result = getWords( ctgry );
    const num = getRandomInt(0,result.length); --this doesn't work
    return result[num];
};


console.log("Sample text: "   getWord());

CodePudding user response:

Try to use async await for your getWords function:

async function getWords(ctgry) {
  try {
    return await Card.find({ category: ctgry });
  } catch (err) {
    console.log(err);
  }
}

async function getWord(ctgry) {
  const result = await getWords(ctgry);
  const num = getRandomInt(0, result.length);
  return result[num];
}

CodePudding user response:

What you seem to be doing here is that you're fetching all the documents from the Card model for a particular category and picking a random one from it, which I wouldn't recommend. Not sure what data you're storing here, but what if your app grows to a point where there are a million documents in your cards collection? You wouldn't fetch them all in memory and pick a random one.

A good practice while using any database is to try to only fetch as much data is required. There's no way to fetch a random document from a query in mongodb from what I know, but there's a way to do this (inspired from this answer which I recommend you read).

async function getRandomWord(ctgry) {
  const count = await User.count({
    "category": ctgry,
  }).exec();
  const random = Math.floor(Math.random() * count);
  return User.findOne({
    "category": ctgry,
  }).skip(random).exec();
}
  • Related