0

I want to get data that equals to question. For some reason it get everything out.

My Schema

    userID: String,
    questionAdd: [{
        question: String,
        answer: String,
    }], 

My code

var test2 = "What fast food chain has the most locations globally?";
    await Data.findOne({
        questionAdd: {
            $elemMatch: {
                question: {$regex: test2, $options: 'i'}
            }
        }
    },(err, data)=>{
        if(data){
            var getData = data.toString();
            console.log(getData);
        }
    })

Please help me!...

I have fix my code, i don't know there any way to get multi result in array object or not, but i change my Schema

    userID: String,
    question: String,
    answer: String

my code after:

let messageArgs1 = args.join(' ');
    var outString = messageArgs1.replace(/[`~!@#$%^&()_|+\-=?;'",.<>\{\}\[\]\\\/]/gi, '');
    var messageArgs2 = outString.toLowerCase();
    var messageArgs = messageArgs2.toLowerCase();
    if(messageArgs=="") return message.channel.send("Please type your question!");
    await Data.find({
            question:{$regex: messageArgs} 
        },{question: 1, answer: 1, _id:0}, (err, data)=>{
            if(!data){
                console.log(data);
                return message.channel.send(`Nope!`);
            }  
            else{
                //do something
            }
      }).limit(9);
}
  • Please remember that the $regex tag in the findOne function needs a valid regular expression aka regex. Can you please specify what test2's value is? Refer to https://stackoverflow.com/questions/38497650/how-to-find-items-using-regex-in-mongoose for usage examples. – D J Jun 29 '21 at 14:43
  • @DJ i make test2 become a string but still like that, i find a solution that like this: await Data.find({"questionAdd.question": messageArgs},{ questionAdd: { $elemMatch: { question: messageArgs } } }, (err, data)=>{ if(!data){ return message.channel.send(`Nope!`); } else{ //do something } }) – Và Thi Thi Jun 29 '21 at 16:59
  • Which get the question and answer out but can't get multi result, only get 1 and much equals to the one that got save to database – Và Thi Thi Jun 29 '21 at 17:01
  • in that case, use `find()` instead of `findOne()` to get multiple results. – D J Jun 30 '21 at 01:24
  • @DJ still like that, i think problem was my schema so i change it, now it work perfect. Anyway thanks for your help too – Và Thi Thi Jun 30 '21 at 10:30

0 Answers0