[英]Mongoose - use a post method to create a new empty collection
正在使用的圖書館: 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"
},
..................................
如何使用我的帖子設置架構並防止創建文檔?
正如您所見,Mongoose在需要將文檔保存到它之前不會創建模型的集合。 但是,您可以使用本機MongoDB驅動程序中的Db#createCollection
方法顯式創建集合,該驅動程序可通過mongoose.connection.db
訪問:
mongoose.connection.db.createCollection(collection_name, (err) => {...});
Mongoose似乎在某些數據訪問操作需要的時候創建了一個仍然缺失的集合。 所以對我來說,(使用v4.5.9)這適用於:
mongoose.connection.db.findOne({}).then(...).catch(...);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.