【问题标题】:Seeing array elements in mongoose js在猫鼬js中查看数组元素
【发布时间】:2013-08-17 22:06:53
【问题描述】:

所以我有这个线程架构(它几乎是一个聊天室:)

var threadSchema = mongoose.Schema({
    messages: [{
        message:String,
        type:String
    }],
    point_id:String
});

我编译成模型如图:

var Thread = mongoose.model('Thread',threadSchema);

我的问题是当我像这样访问线程对象中的消息元素时:

console.log(thread_instance.messages);

它打印出'[object Object]'。即使我在浏览器中解析它也会这样做;它实际上是返回那个字符串 '[object Object]'。

我相信这与我如何推送到数组有关:

this_thread.messages.push({message:data.message,type:data.type});

我的写作/阅读方式有什么问题?非常感谢您的宝贵时间。

【问题讨论】:

  • 直接在mongo中查询数据是什么样子的?
  • 当我运行 db.threads.find() 我得到: { "__v" : 4, "_id" : ObjectId("520dc4921ea8dc0000000002"), "messages" : [ "[object Object]" , "[object Object]", "[object Object]", "[object Object]" ], "point_id" : "520dc4921ea8dc0000000001" } 数组中的每个元素都显示为一个对象。
  • 数据对象是什么样的?
  • 这就是问题所在。它实际上是字符串“[object Object]”。我只需要通过将对象存储为字符串并使其成为字符串数组来破解它。

标签: javascript mongoose


【解决方案1】:

我认为这里的问题是您的数组包含一个对象,其中一个键是“类型”。 type 被 mongoose 用来告诉它架构中的事物的类型是这样的:

var ExhibitSchema = new Schema({
    title  : { type: String, trim: true }
    , description : { type: String, trim: true }
    , discussion  :   {type: Schema.Types.ObjectId, ref: "Discussion"} 
    , views: {type: Number, default: 0}

所以在你的情况下,你告诉猫鼬你有一个字符串类型的messages 数组。它可能只是忽略了message:String 部分。当您将内容添加到该数组中时,它会在其上调用 toString() 来存储它。这就是您在数据库中看到["[object Object]", "[object Object]" 的原因。

通过将架构更改为如下所示来修复它:

var threadSchema = mongoose.Schema({
    messages: [{
        message:{ type: String},
        type:{ type: String}
    }],
    point_id:String
});

【讨论】:

    【解决方案2】:

    messages实际上是一个对象数组,所以你可以像这样指定messages数组的索引

    console.log(thread_instance.messages[0]);
    

    如果messages 数组包含多个元素,您需要一个常规的 for 循环

    for (var i = 0; i<thread_instance.messages.length; i++) {
      // use i as an array index
      console.log(thread_instance.messages[i]);
    }  
    

    所以将所有代码组合在一起,代码将如下所示

    Thread.find(function (err, thread_instance) {
    
        for (var i = 0; i<thread_instance.messages.length; i++) {
          // use i as an array index
          console.log(thread_instance.messages[i]);
        }  
    
    })
    

    【讨论】:

    • 正如他在评论中指出的那样,[object Object] 实际上存储在数据库中
    猜你喜欢
    • 2016-05-14
    • 2021-11-17
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 2022-01-25
    • 2018-05-28
    • 2021-03-04
    • 2018-09-19
    相关资源
    最近更新 更多