【问题标题】:Mongoose casting array to string when using $set使用 $set 时 Mongoose 将数组转换为字符串
【发布时间】:2014-01-09 23:14:19
【问题描述】:

我有我的模型:

var QuestionSchema = new Schema({
    title: String,
    question: String,
    answers: [String],
    set_id: String
});

而我是这样更新的:

questionModel.update({
    _id: id
}, {
    $set: {
        title: req.body.title,
        question: req.body.question,
        answers: req.body.answers
    }
}, function (err, numAffected) {

});

我检查了req.body.answers,它是一个数组,但是,它似乎以foo,bar 的形式保存在数据库中,就像是一个字符串,而不是一个数组!

有什么想法吗?

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:
    answers: req.body.answers[0]
    

    是最终的解决方法,不知道为什么!?如果有人能解释为什么它来自带有输入的表单:name="answers[]" 被传递为 [[foo, bar]]...

    【讨论】:

      【解决方案2】:

      我怀疑因为您在架构定义中使用了“[String]”而不是“Array”,所以当您去更新模型时,数组被转换为字符串,而不是被保存为数组.试试下面的:

      var QuestionSchema = new Schema({
         title: String,
         question: String,
         answers: Array,
         set_id: String
      });
      

      看起来你只会在定义元属性的模式类型周围使用方括号:

      var animalSchema = new Schema({
         name: String,
         type: String,
         tags: { type: [String], index: true } // field level
      });
      

      【讨论】:

        猜你喜欢
        • 2018-06-08
        • 2019-10-28
        • 2017-01-29
        • 2016-03-23
        • 2019-01-06
        • 1970-01-01
        • 2017-11-27
        • 1970-01-01
        相关资源
        最近更新 更多