【问题标题】:String value from mongoose document weird behaviour adding in a variable来自猫鼬文档的字符串值添加到变量中的奇怪行为
【发布时间】:2019-06-19 01:54:19
【问题描述】:

我有一个名为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

我必须如何解码这个字符串值?

【问题讨论】:

  • 你能举一个你看到的特殊字符的例子吗?在第二个示例中,您似乎没有添加“#”
  • 在第二个示例中,我删除了 #。我不使用任何其他特殊字符。在示例中,hashtags[0].name = 'Lula'和hashtags.length == 1

标签: node.js string mongodb mongoose bson


【解决方案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

的属性

【讨论】:

  • 它可以将 for...in 更改为 noticia.hashtags.forEach(hashtag => {}) 。谢谢!
猜你喜欢
  • 2014-07-12
  • 2014-10-07
  • 2013-11-20
  • 1970-01-01
  • 2011-11-15
  • 2016-06-08
  • 1970-01-01
  • 2019-04-11
  • 1970-01-01
相关资源
最近更新 更多