Mongoose: Ошибка с индексами (индексы не создаются)

Созданный на 1 июн. 2017  ·  3Комментарии  ·  Источник: Automattic/mongoose

Привет, у меня есть модель, используемая для хранения лайков для "новостной" модели, например:

import mongoose, { Schema } from 'mongoose';
mongoose.set('debug', true);

var newsLikesSchema = new Schema({
  _news_id: { type: Schema.Types.ObjectId, ref: 'news' },
  condominiums_id: { type: Number, required: true },
  users_id: { type: Number, required: true },
  created_at: { type: Date, default: Date.now },
}, {
  emitIndexErrors: true
});

newsLikesSchema.on('error', function(errorE) {
  console.log('---> index error: ', errorE);
});

newsLikesSchema.on('index', function(errI) {
  console.log('----> new index creating', errI);
});

// Index
newsLikesSchema.index({ _news_id: 1, users_id: 1 }, {unique: true}); // unique like per news/nuser
newsLikesSchema.index({ _news_id: 1, created_at: 1 }); // to sort by news_id and date
newsLikesSchema.index({ users_id: 1 });

var newsLikesM = mongoose.model('newslikes', newsLikesSchema);

module.exports = newsLikesM;

Проблема в том, что индексы не создаются, и у меня нет обратной связи от обратных вызовов «.on ('error')» и «.on ('index')» , они не выполняются.

Версия MongoDB: 3.4.2
Версия Mongoose: 4.10.4
Версия NodeJS: v6.7.0

Самый полезный комментарий

Я устанавливаю autoIndex: false и вызываю Model.ensureIndexes () для построения индекса, но индекс не создается. Это связано с проблемой?

'use strict';

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var uniqueValidator = require('mongoose-unique-validator');

mongoose.set('debug', true);
mongoose.connect('mongodb://localhost:27017/gh3396',{ config: {autoIndex: false} });

// Variables
var ClientSchema = new Schema(
    {
      name : {
        type     : String,
        required : true,
        trim     : true
      },
      organization : {
        type     : String,
        required : true
      }
    }
  )

// Indexes
ClientSchema.index({ "name" : 1, "organization" : 1 }, { unique : true })

// Plugins
ClientSchema.plugin(uniqueValidator, {
  message : 'Name must be unique.'
})

const Client = mongoose.model('Client', ClientSchema);

Client.ensureIndexes()
Client.on('index', function(err){
console.log(err)
})

new Client({
  name: 'a',
  organization:'a'
}).save().then((result) => {
  console.log(result)
}, (err) => {
  console.log(err)
})

и он просто создает индекс _id по умолчанию:

> use gh3396
switched to db gh3396
> show collections
clients
> db.clients.getIndexes()
[
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "gh3396.clients"
    }
]

Любые идеи?
Версия MongoDB: 3.2.1
Версия Mongoose: 4.10.3
Версия NodeJS: v6.7.0

Все 3 Комментарий

У меня тоже была проблема с созданием индекса. В моем случае это было связано с schema.options.autoIndex.
schema.options.autoIndex = false для моих таблиц, и я вызываю sureIndexes в отдельном процессе.
Однако индексы не были созданы, поскольку он все еще проверял флаг autoIndex.

Вы можете проверить, решает ли # 5324 вашу проблему.

Я устанавливаю autoIndex: false и вызываю Model.ensureIndexes () для построения индекса, но индекс не создается. Это связано с проблемой?

'use strict';

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var uniqueValidator = require('mongoose-unique-validator');

mongoose.set('debug', true);
mongoose.connect('mongodb://localhost:27017/gh3396',{ config: {autoIndex: false} });

// Variables
var ClientSchema = new Schema(
    {
      name : {
        type     : String,
        required : true,
        trim     : true
      },
      organization : {
        type     : String,
        required : true
      }
    }
  )

// Indexes
ClientSchema.index({ "name" : 1, "organization" : 1 }, { unique : true })

// Plugins
ClientSchema.plugin(uniqueValidator, {
  message : 'Name must be unique.'
})

const Client = mongoose.model('Client', ClientSchema);

Client.ensureIndexes()
Client.on('index', function(err){
console.log(err)
})

new Client({
  name: 'a',
  organization:'a'
}).save().then((result) => {
  console.log(result)
}, (err) => {
  console.log(err)
})

и он просто создает индекс _id по умолчанию:

> use gh3396
switched to db gh3396
> show collections
clients
> db.clients.getIndexes()
[
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "gh3396.clients"
    }
]

Любые идеи?
Версия MongoDB: 3.2.1
Версия Mongoose: 4.10.3
Версия NodeJS: v6.7.0

Да, это дубликат номеров 5324 и 5328. Будет исправлено в 4.10.6.

Была ли эта страница полезной?
0 / 5 - 0 рейтинги