使用 body-parser 访问 mongoose 模式数组

Accessing mongoose schema array with body-parser

这是一个示例模式:

var schema = mongoose.Schema;

var userSchema = new schema ({
username: {type: String},
hobby: [{
    indoor: {
        type: {type: String},
        description: {type: String}
    },
    outdoor: {
        type: {type: String},
        description: {type: String}
    }

}]
});

module.exports = mongoose.model('User', userSchema);

所以,一个非常简单的模式。它要求输入用户名,然后要求用户列出他们的爱好,并分为室内和室外爱好,以及数组内部。

使用 body-parser,我可以在这样的表单输入中获取用户名:

var user = new User();
user.username = req.body.username;

这很简单。但是我如何才能获得阵列内部的爱好呢?我试过:

user.hobby.indoor.type = req.body.type

但这行不通;它只是给我一个错误。任何帮助将不胜感激。

以下代码将帮助您正确访问密钥。由于 hobby 是一个数组,你需要提供一个索引来获取它的对象。点符号适用于对象

user.hobby[0].indoor.type

Js Fiddle: https://jsfiddle.net/x18nyd2e/

所以我最终找到了问题的答案。这是一个操作示例:

var user = new User();
user.username = req.body.username;
user.hobby = {{
    indoor: {
        type: req.body.type,
        description: req.body.description
    }
}];

这就是您如何到达数组内部的 属性。