正在使用的库:Express、Mongoose、Express-Restify-Mongoose
问题:我正在尝试弄清楚如何创建将在 req.body 中提供架构的 POST 请求。我只想创建一个新集合(如果它尚不存在)并强制执行该新模式。
当我使用下面的代码时:
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 使用帖子的 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 在需要将文档保存到模型集合之前不会创建模型集合。但是,您可以使用 Db#createCollection
显式创建集合来自 native MongoDB 驱动程序的方法,可通过 mongoose.connection.db
访问:
mongoose.connection.db.createCollection(collection_name, (err) => {...});
关于javascript - Mongoose - 使用 post 方法创建一个新的空集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35231012/