猫鼬不使用model()创建索引

时间:2019-07-23 16:03:05

标签: mongodb mongoose mongoose-schema

我遇到一个问题,其中 unique 不能与我的Mongoose模式一起使用,并且我能够添加重复项。

在阅读了这篇文章后,我通过在模式末尾调用 init()解决了该问题:http://luxiyalu.com/mongoose-unique-not-working/

根据Mongoose文档:“除非关闭autoIndex,否则此函数负责建立索引。当使用mongoose.model()或connection.model()创建模型时,Mongoose会自动调用此函数。不需要调用它。”

但是,当我在架构之后添加 init()时,即使应该使用 model()自动调用,也会向MongoDB添加唯一索引:

Item.init().then(() => {
  // safe to create users now.
});

这是我的模式:

const mongoose = require('mongoose');

const ItemSchema = mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    refer: 'users'
  },
  itemName: {
    type: String,
    minlength: 1,
    maxlength: 40,
    required: true
  },
  itemPageName: {
    type: String,
    required: true,
    unique: true,
    index: true
  },
  companyName: {
    type: String,
    required: true
  },
  thumbnailFileName: {
    type: String,
    required: true
  },
  tagline: {
    type: String,
    minlength: 1,
    maxlength: 60,
    required: true
  },
  description: {
    type: String,
    minlength: 1,
    maxlength: 260,
    required: true
  },
  topics: [
    {
      type: String,
      required: true
    }
  ],
  website: {
    type: String
  },
  availability: {
    type: String,
    required: true
  },
  makers: [
    {
      type: String
    }
  ],
  twitter: {
    type: String
  },
  facebook: {
    type: String
  },
  instagram: {
    type: String
  },
  date: {
    type: Date,
    default: Date.now
  }
});

ItemSchema.index(
  {
    itemName: 'text',
    companyName: 'text'
  },
  {
    weights: {
      itemName: 5,
      companyName: 1
    }
  }
);

Item = mongoose.model('item', ItemSchema);

module.exports = Item;

// module.exports = mongoose.model('item', ItemSchema);

Item.init().then(() => {
  // safe to create users now.
});

0 个答案:

没有答案