【问题标题】:Mongoose - use a post method to create a new empty collectionMongoose - 使用 post 方法创建一个新的空集合
【发布时间】:2016-05-15 20:02:49
【问题描述】:

正在使用的库: 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"
    },
..................................

如何设置帖子的架构并防止创建文档?

【问题讨论】:

  • 我将架构保存到名为“core_schema”的集合中。当服务器第一次连接到数据库时,这些模式会被加载。不过你没有回答问题。我只想用 post 方法创建一个空集合。有什么想法吗?你不必关闭我的另一个问题只是减少曝光......

标签: javascript node.js mongodb express mongoose


【解决方案1】:

正如您所见,Mongoose 在需要将文档保存到其中之前不会创建模型的集合。但是,您可以使用本机 MongoDB 驱动程序中的 Db#createCollection 方法显式创建集合,该驱动程序可通过 mongoose.connection.db 访问:

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

【讨论】:

    【解决方案2】:

    Mongoose 似乎会在需要进行某些数据访问操作时创建一个仍然缺失的集合。所以对我来说,(使用 v4.5.9)这是可行的:

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

    【讨论】:

      猜你喜欢
      • 2017-01-19
      • 1970-01-01
      • 2013-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-20
      • 2021-05-29
      • 2016-03-04
      相关资源
      最近更新 更多