【问题标题】:Storing Javascript Array of Objects in Mongo DB using Mongoose使用 Mongoose 在 Mongo DB 中存储对象的 Javascript 数组
【发布时间】:2015-08-22 00:05:06
【问题描述】:

我有一个 [{key: ..., type: ..., value: ...}] 形式的数组,并希望将其存储在以下架构的 fields 字段中:

var articleSchema = mongoose.Schema({
  name: {
    type: String,
    unique: true,
    required: true
  },
  updated: {
    type: Date,
    default: Date.now
  },
  pageviews: {
    type: Number,
    default: 0
  },
  fields: [{
    key: String,
    type: String,
    value: String
  }],
  image: String
});

我这样做如下,我的Javascript数组引用为keyValueObj

Article.findOneAndUpdate(
  { name: articleName },
  {
    fields: keyValueObj
  },
  { upsert: true },
  callback
);

但是,数据库中 fields 字段中存储的所有内容都是一个字符串数组,如下所示:["[object Object]"]

如何存储我的 Javascript 数组以使其正确匹配我的猫鼬模式?

【问题讨论】:

  • 您可能应该为字段创建另一个架构,然后执行字段:[fieldsSchema]
  • 您可以将数组解析为 json 或尝试将 de 模式类型更改为 Array (mongoosejs.com/docs/guide.html)

标签: javascript arrays node.js mongodb mongoose


【解决方案1】:

我能够使用 Molda's 使用单独架构的想法来解决此问题。

articleSchema 中更新后的 fields 字段现在如下所示:

fields: [{
  type: Schema.Types.ObjectId,
  ref: 'Field'
}]

然后我将数组转换为模式对象数组,如下所示:

keyValueObj = keyValueObj.map(function(fieldObj){
  return new Field({
    key: fieldObj.key,
    type: fieldObj.type,
    value: fieldObj.value
  });
});

然后我可以将keyValueObj 存储在初始代码中。

【讨论】:

    猜你喜欢
    • 2016-05-21
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    • 2019-05-29
    • 2018-10-13
    • 2015-04-03
    • 2019-09-21
    • 2019-11-23
    相关资源
    最近更新 更多