【发布时间】:2016-05-15 20:02:49
【问题描述】:
正在使用的库: Express、Mongoose、Express-Restify-Mongoose
问题:我试图弄清楚如何创建一个 POST 请求,该请求将在 req.body 中提供架构。如果它尚不存在,我只想创建一个新集合并强制执行该新模式。
当我使用以下代码时:
app.use('/api/v1', function(req, res, next) {
if(req.path[0] === '/' && -1 === req.path.indexOf('/', 1) && req.method === 'POST') {
var collection_name = req.path.substr(1, req.path.length - 1).toLowerCase();
if(mongoose.modelNames().indexOf(collection_name) === -1) {
// only create if model does not exist
console.log(req.body);
var schema = new mongoose.Schema({}, { strict: false, collection: collection_name });
var model = mongoose.model(collection_name, schema);
restify.serve(app, model, { plural: false, name: collection_name });
}
}
next();
});
它还会向该集合发布一个空文档。如果我稍微更改代码以便 var schema 使用 post 的 req.body 来确定 POST 请求不通过的模式:
var schema = new mongoose.Schema(req.body, { strict: false, collection: collection_name });
POST 中的 req.body 在哪里:
{
"update_count": { "type": "String", "required": "false" },
"created_date": { "type": "String", "required": "false" },
"created_by": { "type": "String", "required": "false" },
"updated_date": { "type": "String", "required": "false" },
"updated_by": { "type": "String", "required": "false" }
}
它返回一个错误并且没有完成 POST 请求,因为它还试图使用相同的 req.body 来遵循我刚刚设置的架构并且它想使用 req.body 进入文档。
{
"message": "testcollection3 validation failed",
"name": "ValidationError",
"errors": {
"updated_by": {
"message": "Cast to String failed for value \"[object Object]\" at path \"updated_by\"",
"name": "CastError",
"kind": "String",
"value": {
"type": "String",
"required": "false"
},
"path": "updated_by"
},
..................................
如何设置帖子的架构并防止创建文档?
【问题讨论】:
-
我将架构保存到名为“core_schema”的集合中。当服务器第一次连接到数据库时,这些模式会被加载。不过你没有回答问题。我只想用 post 方法创建一个空集合。有什么想法吗?你不必关闭我的另一个问题只是减少曝光......
标签: javascript node.js mongodb express mongoose