私はイベントアプリケーションをビルドしています。 'イベント'スキーマにはタグのスキーマの配列があります。 1つまたは複数のタグ。Express&Nodejs:スキーマを作成した後にのみ 'next()'を呼び出す方法
イベント:
var EventSchema = new Schema({
...
tags: [{
type: Schema.Types.ObjectId,
ref: 'Tag'
}],
...
}
とタグ:
ユーザーは、イベントに関するすべての情報をイベントミドルウェアに/ POSTにJSONを送るイベントを作成したいvar TagSchema = new Schema({
name:{
type: String,
require: true
},
times:{
type: Number,
default: 0
}
});
//json sent by client to server
{tags:[{name:tag1},{name:tag2}]
2つのイベントが同じ名前を持つことはできないため、特定のmi ddleware私はいくつかのユーザーがすでにタグを作成しているか、実際にタグを保存する必要があるかどうかを確認します。
// add the tags
addTags(req, res, next) {
var myBody = req.body;
if (myBody.tags) {
const len = myBody.tags.length
if (len > 0) {
// we need to search and store a tag if is has not already created
for (let i = 0; i < len; i++) {
let currentTag = myBody.tags[i]
// find the currentTag in the DB
Tag.findOne({
name: currentTag.name
}, (err, find) =>{
if (err) return next(err)
// if we not find it
else if (!find) {
// create new one
let newTag = new Tag({
name: myBody.tags[i].name
})
utils.saveModel(newTag, next, (saved) => {
// store it back the ref
req.Event.tags.push(saved._id)
})
} else {
// store the ref
req.Event.tags.push(find._id)
}
})
}
console.log('tags added!.');
next()
}
} else {
next()
}
},
私の問題は、どのように私はすべてのタグをチェックした後にのみ '次の'を呼び出すことができますか?出来ますか?あなたはおそらくpromisesを使用する必要がありますが、あなたはあなたの現在のアプローチを変更したくない場合は、あなたがそれを呼ばれるコールバックをカウントすることにより、昔ながらの方法で、行うことができますあなたの
は非同期モジュール – Alex
を見て、[約束](http://mongoosejs.com/docs/promises.html) – Matt
は私がしようとしている、あなたは –