javascript - Mongoose - use a post method to create a new empty collection -
libraries in use: express, mongoose, express-restify-mongoose
problem: trying figure out how create post request provide schema in req.body. want create new collection if not exist , enforce new schema.
when use following code:
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) { // create if model 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(); });
it posts empty document collection. if change code ever var schema uses post's req.body determine schema post request not go through:
var schema = new mongoose.schema(req.body, { strict: false, collection: collection_name });
where req.body post is:
{ "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" } }
which returns error , not complete post request because trying use same req.body follow schema i've set , wants use req.body enter document.
{ "message": "testcollection3 validation failed", "name": "validationerror", "errors": { "updated_by": { "message": "cast string failed value \"[object object]\" @ path \"updated_by\"", "name": "casterror", "kind": "string", "value": { "type": "string", "required": "false" }, "path": "updated_by" }, ..................................
how can set schema post , prevent document being created?
as you've seen, mongoose won't create model's collection until needs save document it. however, can create collection explicitly using db#createcollection
method native mongodb driver that's accessible via mongoose.connection.db
:
mongoose.connection.db.createcollection(collection_name, (err) => {...});
Comments
Post a Comment