0

I Have a Message Schema with 2 type message: text and voice, How Should I get value of text?

text data example:

{
    "_id" : ObjectId("5a8ea03d2601be24b086ccd4"),
    "userId" : 20,
    "text" : "Hi",
    "__v" : 0
}

voice data example:

   {
        "_id" : ObjectId("5a8ea03d2601be24b086ccd4"),
        "userId" : 20,
        "voice" : "d2601be24bd22601be24b",
        "__v" : 0
    }

Code:

Message
  .find({userId: '20'}, {_id: 0, text: ''})
  .exec((err, obj) => {
    if (err) {
      console.log(err);
    }

    for (const val of Object.values(obj)) {
      console.log(val.text);
    }
  });

output:

Hi    // for text
undefined  // for voice

I have All Type of Message in Output, How Should I get all text value? (not voice)?

Saeed Heidarizarei
  • 8,406
  • 21
  • 60
  • 103

1 Answers1

1

Couple of options, you could add an if statement within your for loop e.g.

for (const val of Object.values(obj)) {
    if(val.text) console.log(val.text);
}

Alternatively you could adjust your database query to only select messages with a non-empty text string e.g.

Message
  .find(
    {
       userId: '20',
       text: {
           $exists: true,
           $ne: ''
    },
    {_id: 0, text: ''}
  )

Note: my query may not be quite right as I didn't test it, but it would be something to that effect. See: Find MongoDB records where array field is not empty for similar concept.

foxinatardis
  • 156
  • 8