简体   繁体   中英

Mongoose - use a post method to create a new empty collection

Libraries in use: Express, Mongoose, Express-Restify-Mongoose

Problem: I am trying to figure out how to create a POST request that will provide the schema in the req.body. I want to simply create a new collection if it does not already exist and enforce that new schema.

when I use the 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) {
      // 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();
});

It also posts an empty document to that collection. If I change the code ever so slightly so that var schema uses the post's req.body to determine the schema the POST request does not go through:

  var schema = new mongoose.Schema(req.body, { strict: false, collection: collection_name });

Where the req.body from the 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 an error and does not complete the POST request because it is also trying to use that same req.body to follow the schema I've just set AND it wants to use the req.body to enter into the document.

{
  "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"
    },
..................................

How can I set the schema with my post and also prevent a document from being created?

As you've seen, Mongoose won't create a model's collection until it needs to save a document to it. However, you can create the collection explicitly using the Db#createCollection method from the native MongoDB driver that's accessible via mongoose.connection.db :

mongoose.connection.db.createCollection(collection_name, (err) => {...});

Mongoose seems to create a still missing collection any time it is needed for some data access operation. So for me, (using v4.5.9) this works:

mongoose.connection.db.findOne({}).then(...).catch(...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM