庫:快遞,貓鼬,快速-的RESTify,貓鼬貓鼬 - 使用POST方法來創建一個新的空收集使用
問題:我試圖找出如何創建一個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架構使用後的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方法創建一個空集合。有什麼想法嗎?你不必關閉我的另一個問題,只是減少曝光.... –