Home > Back-end >  Mongoose: How to find() based on nested object value
Mongoose: How to find() based on nested object value

Time:10-11

I have a schema desing like this:

const UserDataFrameWork = new mongoose.Schema({
HighScores: {
        Dodge: {
            TenCent: {type:Number, default: 0},
            FiftyCent: {type:Number, default: 0},
            Dolsu: {type:Number, default: 0},
            FiveDolsu: {type:Number, default: 0},
            TenDolsu: {type:Number, default: 0},
            FiftyDolsu: {type:Number, default: 0},
        },
        example: { 
            test: {type:Number, default: 0}
          }
       }
}

const User = mongoose.model('User', UserDataFrameWork)

module.exports = User

I am trying to find the users that have highscore of 0 in Dodge.TenCent like this:

const express = require('express')
const router = express.Router();
const DB = require('../models/User')

router.get('/', async (req,res) =>{

const Tgames = await DB.find({"HighScores.Dodge.TenCent": 0})

console.log(Tgames)
res.render('testejs.ejs')

})

module.exports = router;

This doesn't work, I can't figure out how to find based on the value of nested object. Is it even possible to have object inside of object in mongoose schema? I am pretty new to mongoose so sorry if I'm doing something wrong? Any help is appreciated!

CodePudding user response:

One of my nested queries looks like this:

let ppdata = await Pallet.find({sscc: {$in: ssccArray}, 'po.edi_file_name': /PO/i }, ' sscc po.season po.edi_file_name').slice('po', -1).lean().exec();

Have you tested:

const Tgames = await DB.find({"HighScores.Dodge.TenCent": 0}).exec() 

CodePudding user response:

I kind of found the answer! Not to my question but, I'm not stuck with this anymore. So when I tried to find() something with the value of 0 it was not returning anything, but when I tried finding something with value two it returned. It is not a problem if I can't find anything with the value 0 because I believe it is the same as undefined, because I have set the default to 0.

  • Related