Search code examples
node.jsstringmongodbmongoosebson

String value from mongoose document weird behaviour adding in a variable


I have a mongo document called New which has a sub document called hashtags which has th value name which is a string. I am trying to add all the hashtags belongs to a new in a variable but is adding extra characters (seems that the name string value is not well decoded from the bson or something like that).

New document:

var newSchema = new Schema({
    ...
    hashtags: [{
        type : mongoose.Schema.ObjectId,
        ref: 'Hashtag'
    }]
});

Hashtag document:

    var mongoose = require('mongoose')
    var Schema = mongoose.Schema

    var hashtagSchema = new Schema({
        color:  {
            type: String,
            default: '#000000'
        },
        name:  {
            type: String
        }
    });
    var hashtag = mongoose.model('Hashtag', hashtagSchema )

    module.exports = hashtag

Snniped testing code:

    docs.forEach(noticia => {
        if(noticia.hashtags.length > 0){
            for(i in noticia.hashtags){
                if(noticia.hashtags[i] && noticia.hashtags[i].name){
                    text +=  '#' + noticia.hashtags[i].name.replace(/\s/g,'') + ' '
                }
            }
        }
    })
console.log(text)

Console output:

#Lula #toBSON #_cast #_markModified #_registerAtomic #$__getAtomics #hasAtomics #_mapCast #push #nonAtomicPush #$pop #pop #$shift #shift #pull #splice #unshift #sort #addToSet #set #toObject #inspect #indexOf #pull

I have tried to apply noticia.hashtags[i].name.replace(/\s/g,'').toString() :

    docs.forEach(noticia => {
        if(noticia.hashtags.length > 0){
            for(i in noticia.hashtags){
                if(noticia.hashtags[i] && noticia.hashtags[i].name){
                    text +=  noticia.hashtags[i].name.toString() + ' '
                }
            }
        }
    })

Console output LulatoBSON_cast_markModified_registerAtomic$__getAtomicshasAtomics_mapCastpushnonAtomicPush$poppop$shiftshiftpullspliceunshiftsortaddToSetsettoObjectinspectindexOfpull

How I have to decode this string value?


Solution

  • The for...in statement iterates over all non-Symbol, enumerable properties of an object.

    var string1 = "";
    var object1 = {a: 1, b: 2, c: 3};
    
    for (var property1 in object1) {
      string1 += object1[property1];
    }
    
    console.log(string1);
    // expected output: "123"
    

    You are iterating over the properties of noticia.hashtags