The safest way is, as someone commented, to record it or write it down. But when I get an idea like that I like to challenge myself and try to remember it without documenting.
(I do this in the shower all the time too, just for fun)
So to answer your question:
It's easy to forget a bunch of pitches in a row, but it's not that hard to translate it into simpler information, that you can easily remember. If i were to come up with a melody in my head as I'm falling asleep i would do the following:
- Melody: Listen to the melody in your head. What intervals are you using, and more importantly, what interval are you starting with? I almost always remember the melody later when I play/hum the first few intervals, and I usually don't even try to remember the rhythm, it just comes back with the melody.
- Style: What is the feel of the melody, or what is the point of the melody? This step is my favourite, because 9/10 times, when I later try to recall the melody, I almost always find ways to improve upon it, because it wasn't optimal for it's point to begin with.
- Rhythm: Some people have trouble remembering melodics, some people have trouble remembering rhythmics. Find the one that is easier for you and repeat step one with rhythm. Instead of intervals you can think in "groups". Visualize the rhythmic notation and take a mental snapshot of it. I belong to the group that has trouble remembering rhythm, but this step still works for me.
- Instrumentation: This is pretty simple, what instrument do you hear playing your melody? Remember the instruments names, not their sounds.
- Harmony: This is the hardest part imo. But if you are familiar with chord functions or step analysis, you should definitely use that and just get the base chords. You can figure out extensions when you are fully awake.
If you do all of this, you'll have translated your abstract idea to a very concrete list of information. You should have no trouble remembering the melody and in addition you've trained your hearing and your theory skills. Win win!
- Don't care. If you compose a lot you learn to trust your ability to write melodies, and you shouldn't have to celebrate when you "find a good one". Also I've learned that the importance of a good melody is lower than the importance of good orchestration and production (sound)
Hope this helps!