【问题标题】:Recreate models using Mongoose使用 Mongoose 重新创建模型
【发布时间】:2013-09-27 06:47:11
【问题描述】:

我想在删除所有内容后在数据库中重新创建模型。

Mongoose(或 Mongo 本身)实际上是重新创建文档而不是索引。那么有没有办法重置 Mongoose 以便它可以像第一次运行一样重新创建索引?

我使用 dropDatabase 的原因是因为它在测试时看起来更容易。否则我将不得不一一删除所有集合。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    虽然不建议用于生产,但根据您的场景,您可以将 index 属性添加到字段定义中以指定您想要创建索引:

    var animalSchema = new Schema({
      name: String,
      type: String,
      tags: { type: [String], index: true } // field level
    });
    
    animalSchema.index({ name: 1, type: -1 }); // schema level
    

    或者,

    var s = new Schema({ name: { type: String, sparse: true })
    Schema.path('name').index({ sparse: true });
    

    或者,您可以拨打Model (docs) 上的ensureIndex

    Animal.ensureIndexes(function (err) {
        if (err) return handleError(err);
    });
    

    【讨论】:

    • 我切换到一种方法,在测试开始之前通过脚本删除测试数据库。但就像反馈一样,您的第一个解决方案也不起作用。我认为一旦创建了模型,它就会缓存它并且不检查索引。 ensureIndexes 方法可能有效,所以我接受这个作为答案。
    猜你喜欢
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 2014-04-03
    • 2011-10-21
    • 1970-01-01
    • 2011-06-28
    • 2014-09-21
    • 1970-01-01
    相关资源
    最近更新 更多