Reputation: 13
Hi the mongodb query works fine in compass but not with mongoose and nodejs here's my code
const scanschema = new mongoose.Schema({
toreward: [{
highest: {
type: String,
required: true
},
}]
})
const scanmodel = mongoose.model('Scan', scanschema);
const findonescan = async (previous) => {
const scans = await scanmodel.find();
console.log(scans[0].toreward);
console.log('alksdj');
const highestt = await scanmodel.findOne({
toreward: { highest: scans[0].toreward[0].highest }
});
console.log('hi');
console.log(highestt);
}
console.log(highestt)
returns null while i inserted the following data into mongodb
{
"_id": {
"$oid": "67825beb2953246ae8abaa43"
},
"toreward": [
{
"highest": "040144e569a0a32442d87ae69e911ac8c9dd978e4f03dc8b6354fddb3ef3abbd3ab235aa9b97d587b75625c611cc731866dc5c480c857cf42f6aacdc6fb84694669610016bd3b2408aa5da21041129063a0de7f0fc33f238cc7918730a79bb493f2492daff963c96777bb03c10b16972773102f0f0f7293a548fd936a3255314c53a3eff2e"
}
]
}
Upvotes: 0
Views: 38
Reputation: 51260
You can work with dot notation:
const highestt = await scanmodel.findOne({ "toreward.highest": scans[0].toreward[0].highest });
or $elemMatch
:
const highestt = await scanmodel.findOne({
"toreward": {
"$elemMatch": {
"highest": scans[0].toreward[0].highest
}
}
});
You may consider to create a toreward
schema for the nested object in the toreward
array.
const torewardSchema = new mongoose.Schema({
highest: {
type: String,
required: true
}
})
const scanschema = new mongoose.Schema({
toreward: [torewardSchema]
})
Upvotes: 0