ensureIndex causes error

牧云@^-^@ 提交于 2019-12-25 07:39:47

问题


This is my code:

this._db = db;
this._collection = this._db.collection("Topics");
this._collection.ensureIndex( { slug: 1 }, { unique: true }, function(error) {
  if (error) {
   console.error(error);
  }});

When I use an insert:

self._collection.insert(topic, function (err, docs) {
    if (err) {
        topic.slug = shortId.generate() + "-" + topic.slug;
        self._collection.insert(topic, function (err, docs) {
            return done(err, docs);
        });
    }
    return done(err, docs);
});

I get this error inside the "docs" response, beside the content of "topic":

[Error: Connection was destroyed by application]

Note that if I remove the unique index the response works correctly...

Done is a callback:

    function (err, topic) {
        console.log(topic);
        assert.equal(topic.length, 1);
        assert(topic[0]._id);
        assert.equal(topic[0].title, "Topic title");
        assert.equal(topic[0].slug, "topic-title");
        assert.equal(topic[0].markdown, "text **bold**");
        assert.equal(topic[0].html, "<p>text <strong>bold</strong></p>");
        assert.equal(topic[0].tags[0], "tag1");
        assert.equal(topic[0].tags[1], "tag2");
        done(err);
    });

What am I doing wrong?

Edit: this is the function which causes problems:

TopicManager.prototype.save = function (topics, done) {

    var self = this;

    // Make sure topics is an array
    topics = (Array.isArray(topics)) ? topics : [topics];

    // For each topic perform upsert
    async.map(topics, function (topic, done) {

        // Parse Markdown
        topic.html = ghm.parse(topic.markdown);

        // Upsert topic
        if (topic._id) {
            self._collection.update({slug: topic.slug}, topic, function (err, docs) {
                return done(err, docs[0]);
            });
        } else {

            // Generate unique slug
            topic.slug = slug(topic.title).toLowerCase();

            self._collection.insert(topic, function (err, docs) {
                if (err) {
                    topic.slug = shortId.generate() + "-" + topic.slug;
                    self._collection.insert(topic, function (err, docs) {
                        return done(err, docs);
                    });
                }
                return done(err, docs);
            });
        }

    }, done);

};

来源:https://stackoverflow.com/questions/24477420/ensureindex-causes-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!