猫鼬文档的字符串值怪异行为添加了一个变量

时间:2019-06-18 16:58:27

标签: node.js string mongodb mongoose bson

我有一个名为New的mongo文档,该文档具有一个名为hashtags的子文档,该子文档的值为name,它是一个string。我试图在一个变量中添加所有属于新标签的#标签,但又添加了额外的字符(似乎name字符串值不能很好地从bson或类似的字符中解码出来)。

新文档

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

标签文档

    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

狙击测试代码

    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)

控制台输出

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

我尝试申请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() + ' '
                }
            }
        }
    })

控制台输出 LulatoBSON_cast_markModified_registerAtomic$__getAtomicshasAtomics_mapCastpushnonAtomicPush$poppop$shiftshiftpullspliceunshiftsortaddToSetsettoObjectinspectindexOfpull

我该如何解码此字符串值?

1 个答案:

答案 0 :(得分:1)

  

for ... in 语句迭代对象的所有非符号可枚举属性。

var string1 = "";
var object1 = {a: 1, b: 2, c: 3};

for (var property1 in object1) {
  string1 += object1[property1];
}

console.log(string1);
// expected output: "123"

您正在遍历 noticia.hashtags

的属性