[英]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.