【问题标题】:Mongoose not saving array of objects猫鼬不保存对象数组
【发布时间】:2018-07-12 15:06:00
【问题描述】:

我是mongodb 的新手,这是我的schema

import mongoose, { Schema } from 'mongoose';

const SomeSchema = new Schema({

  vDocs: [{type: String , required: true,  }],
  vBelongsTo: { type: Schema.Types.ObjectId, ref: 'User' }

});

const SomeSchema = mongoose.model('BlaBla', SomeSchema);
export default SomeSchema;

mongoose 只保存像 ["bla", "bla"] 这样的简单数组 vDocs

但我想将类似 [{key: val}, {key: val}] 的内容保存在 vDocs 两者都是数组我不知道为什么不工作

【问题讨论】:

标签: node.js mongoose


【解决方案1】:

您已将 type 声明为一个字符串,但您正在尝试保存一个对象

 //Try This
 let newObj = new SomeSchema
 newObj.vDocs = JSON.stringify(whatEverObject)
 SomeSchema.save().then(function(v){
        // whatever 
    })

【讨论】:

  • 它有效,但是当我必须检索时,我必须使用 JSON.parse()
【解决方案2】:

我遇到了同样的问题,我通过更改 type: Array 解决了它。以下应该有效:

vDocs: [{ type: Array, required: true }],

【讨论】:

    猜你喜欢
    • 2021-01-30
    • 1970-01-01
    • 2014-07-26
    • 2020-07-27
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    相关资源
    最近更新 更多