0

Using this in mongoose:

const motherLevel = await db.Mother.findOne({});

const b = motherLevel.cards[level];

console.log(b);

I get this array:

[ { cards: [ [Object] ], _id: 60ef57c59f44361488e5cf96, unit: 1 } ]

Then I want to get the object inside based on unit: 1 so I use this one:

const c = motherLevel.cards[level].findOne({ unit: 1 });

But it doesn't return any result!!!

How can I fix this?

EDIT:

I have this structure in my collection (Note that I have only this single collection and I want to push some data into the cards nested deeply inside)

enter image description here

As you see I want to go to each of the levels first for instance into the starter level in our case...

Then I want to pick the unit 1 and push a new card into the cards which is a part of the unit one object right?

So far I can get the level which is the array containing different units but I cannot pick that unit to push my card into it...

4
  • What does console.log(c) say? Commented Jul 15, 2021 at 14:42
  • it returns nothing........ Commented Jul 15, 2021 at 14:44
  • It would either say undefined or an empty array or null or maybe throw an error. I don't think it will return nothing right? Commented Jul 15, 2021 at 14:45
  • I think maybe just an empty line ... Commented Jul 15, 2021 at 14:46

1 Answer 1

1

You are using findOne on a javascript array but findOne is a method of mongoose/mongodb at following line

const c = motherLevel.cards[level].findOne({ unit: 1 });

if you want find that unit 1 is exists in the motherLevel.cards array you should use following, this will return the first match of card that have unit 1

const c = motherLevel.cards.find(card=>c.unit===1)

or if you want to all cards that have unit 1 you can use filter like following, this will return all the cards that have unit 1

const c = motherLevel.cards.find(card=>c.unit===1)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.