์๋ ํ์ธ์ ์ ๋ ๋ค์๊ณผ ๊ฐ์ "๋ด์ค" ๋ชจ๋ธ์ ๋ํ ์ข์์๋ฅผ ์ ์ฅํ๋ ๋ฐ ์ฌ์ฉ๋๋ ๋ชจ๋ธ์ด ์์ต๋๋ค.
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')" ์ฝ๋ฐฑ์์ ํผ๋๋ฐฑ์ด ์์ด์ ์คํ๋์ง ์๋๋ค๋ ๊ฒ์ ๋๋ค.
๋ชฝ๊ณ DB ๋ฒ์ : 3.4.2
๋ชฝ๊ตฌ์ค ๋ฒ์ : 4.10.4
NodeJS ๋ฒ์ : v6.7.0
์ธ๋ฑ์ค ์์ฑ์๋ ๋ฌธ์ ๊ฐ ์์์ต๋๋ค. ์ ๊ฒฝ์ฐ์๋ 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"
}
]
์ด๋ค ์์ด๋์ด?
๋ชฝ๊ณ DB ๋ฒ์ : 3.2.1
๋ชฝ๊ตฌ์ค ๋ฒ์ : 4.10.3
NodeJS ๋ฒ์ : v6.7.0
์, ์ด๊ฒ์ #5324 ๋ฐ #5328์ ๋ณต์ ๋ณธ์ ๋๋ค. 4.10.6์ผ๋ก ์์ ๋ฉ๋๋ค.
๊ฐ์ฅ ์ ์ฉํ ๋๊ธ
autoIndex:false ๋ฅผ ์ค์ ํ๊ณ Model.ensureIndexes() ๋ฅผ ํธ์ถํ์ฌ ์ธ๋ฑ์ค๋ฅผ ๋น๋ํ์ง๋ง ์ธ๋ฑ์ค๋ ์์ฑํ์ง ์์ต๋๋ค. ๋ฌธ์ ์ ๊ด๋ จ์ด ์์ต๋๊น?
๊ธฐ๋ณธ์ ์ผ๋ก _id ์ธ๋ฑ์ค๋ฅผ ์์ฑํฉ๋๋ค.
์ด๋ค ์์ด๋์ด?
๋ชฝ๊ณ DB ๋ฒ์ : 3.2.1
๋ชฝ๊ตฌ์ค ๋ฒ์ : 4.10.3
NodeJS ๋ฒ์ : v6.7.0