1
我正在創建一個簡單的博客,其中包含標籤的帖子。貓鼬添加對象數組
var postSchema = new Schema ({
title: { type: String, required: true },
content: { type: String, required: true },
tags: [{ type: Schema.Types.ObjectId, ref: 'Tag' }]
});
當用戶發佈帖子時,我將標籤作爲標籤名稱數組獲取。如何循環這些標籤並創建它們,並在第一次保存時將它們添加到帖子中?
我已經試過這樣:
var post = Post({
title: data.title,
content: data.content
});
data.tags.forEach(function(name) {
Tag.findOrCreate({ name: name }, function(err, tag, created) {
post.tags.push(tag);
post.save(function(err) {
if (err) throw err;
console.log('Post saved!');
});
});
});
但是,這迫使我再次保存後每個標籤。有沒有辦法只保存一次?
@ProvocativePanda如果您還有其他問題,請使用[Ask Question](http://stackoverflow.com/questions/ask)鏈接發佈。您剛剛瞭解到需要「流量控制」來尊重異步執行。如果你有更具體的問題要求他們形成併發布他們,並有人會回答。 –