node.js - How to create a persistent unique index in MongoDB -
node.js - How to create a persistent unique index in MongoDB -
disclaimer : i'm using mongoose less 48h.
i have model looks :
var mongoose = require('mongoose'); var schema = mongoose.schema; //schema definition var categoryschema = new schema({ name: string, url: { type: [string], index: true }, extra: array, frequency: number, last_processed: date }); // model definition var category = mongoose.model('categories', categoryschema);
when app launches, has method automatically update collection, using js file structured next (js file not under control):
var categories = { retailer: 'ret1', name: 'c1', url: 'url1', extra: ['tag1'], frequency: 2, last_processed: '' }, { retailer: 'ret2', name: 'c2', url: 'url2', extra: ['tag2'], frequency: 2, last_processed: '' }, ........ ]; module.exports = categories;
i create records using loop :
var category = mongoose.model('categories'); (var j = 0; j < categories.length; j++) { new category(categories[j]).save(); }
my problem next :
when launch app first time, db.categories.count()= 308 (as should be). if close app , relaunch however, count()=616, duplicates records. thought using index avoid behaviour, apparently not. documentation on indexes isn't clear me, coming rdb background. see in debug index created : mongoose: categories.ensureindex({ url: 1 }) { safe: undefined, background: true }
how can create persistent unique index on collection never have duplicates? after simple startup routine, writing on table constantly, have recreate index after each write?
update after more research :
i have no duplicates in 308 urls write , start empty db.
you can define index unique:
var categoryschema = new schema({ name: string, url: { type: string, index: { unique: true } }, extra: array, frequency: number, last_processed: date });
then, given add together callback save()
for (var j = 0; j < categories.length; j++) { new category(categories[j]).save(function(err, doc) { console.error(err); }); }
you see next printed
{ [mongoerror: insertdocument :: caused :: 11000 e11000 duplicate key error index: test.categories.$url_1 dup key: { : "url2" }] name: 'mongoerror', code: 11000, err: 'insertdocument :: caused :: 11000 e11000 duplicate key error index: test.categories.$url_1 dup key: { : "url2" }' }
you can utilize findoneandupdate
which, given alternative upsert: true
, either create or update object. if don't want update skip because category exists using save()
enough.
for (var j = 0; j < categories.length; j++) { category.findoneandupdate( { url: categories[j].url }, categories[j], { upsert: true }, function(err, doc) { console.error(err); } ); }
node.js mongodb mongoose
Comments
Post a Comment