这是我的代码:
this._db = db;
this._collection = this._db.collection("Topics");
this._collection.ensureIndex( { slug: 1 }, { unique: true }, function(error) {
if (error) {
console.error(error);
}});
当我使用插入时:
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);
});
我在" docs"中收到此错误响应,除了"主题"的内容:
[Error: Connection was destroyed by application]
请注意,如果删除唯一索引,则响应正常...
完成回调:
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);
});
我做错了什么?
编辑:这是导致问题的功能:
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);
};