【问题标题】:Error adding array to MongoDB / Mongoose collection将数组添加到 MongoDB / Mongoose 集合时出错
【发布时间】:2016-02-27 11:16:54
【问题描述】:

我正在尝试将数组添加到 Mongo 文档中,但收到错误 "Cast to Array failed for value "[object Object],[object Object]" at path "vendors""

这是我的模型:

module.exports = {
  attributes: {
    vendors: {
      type: [String]
    },
    description: {
      type: String
    }
  }
};

这是我要创建的代码:

var vendors = ko.observableArray(['foo','bar']);
var desc = ko.observable('yadda yadda yadda');
var dto = {
    data: {
      vendors: vendors(),
      description: description()
    }
};
DataService.quoteRequest.create(dto);

【问题讨论】:

  • 您的自定义供应商代码是什么样的?
  • 那是一个错字,应该是供应商。我修好了。
  • 不管淘汰赛,如果我在 DTO 中传递一个普通数组,我会得到同样的错误。
  • 你在哪里定义你的架构?

标签: arrays node.js mongodb knockout.js mongoose


【解决方案1】:

音乐海岸,

我不熟悉 knockout.js,但关于 Mongoose,您似乎并没有定义您的 SchemaModel。您需要执行以下操作:

定义架构

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

var attributesSchema = new Schema({
  vendors: [String],
  description: String
});

创建模型

var Attributes = mongoose.model('Attribute',attributesSchema);

创建和保存文档

//create an attribute document
var attribute = new Attributes(
   { 
     vendors: vendorsArray,
     description: desc
    }
 );

attribute.save(function(err){
if(!err) console.log('Success');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多