我有一个名为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
我该如何解码此字符串值?
答案 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
的属性