使用$ set时,Mongoose将数组转换为字符串

时间:2013-12-08 21:20:50

标签: node.js express mongoose

我有我的模特:

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的形式保存在数据库中,就像在字符串中,而不是数组一样!

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

answers: req.body.answers[0]

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

答案 1 :(得分:0)

我怀疑因为你在架构定义中使用了'[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
});