2017-11-07 9 views
-1

私はmongodbに急速に成長しているコレクションを持っています。私は新しい文書がそれらのコレクションに挿入されたときに特定のアクションを取る必要があります。このような新しいモデルが挿入されたとき、どのように行動を観察してトリガすることができますか?MongoDB + ExpressJS - 挿入を確認する

私はmongo-observerのような古い解決策を発見しましたが、それはかなり古いと思われ、私にとっては役に立たなかったようです。

誰かが比較的新しい、維持管理されたソリューションをお勧めしますか?

+0

質問**オフトピックスタックオーバーフローのためにある書籍、ツール、ソフトウェアライブラリ、チュートリアルや他のオフサイトのリソースをお勧めしますか見つけるために私たちを求めて。代わりに、[問題を説明する](http://meta.stackoverflow.com/questions/254393)、これを解決するためにこれまでに何が行われているか。 –

答えて

-2

npmモジュール - mongohooksを参照できます。

更新:

追加するサンプルコード:

const db = require('mongojs')('mydb', ['members']); // load mongojs as normal 
const mongohooks = require('mongohooks'); 

// Add a `createdAt` timestamp to all new documents 
mongohooks(db.members).save(function (document, next) { 
    document.createdAt = new Date(); 
    next(); 
}); 

// Now just use the reqular mongojs API 
db.members.save({ name: "Thomas" }, function (error, result) { 
    console.log("Created %s at %s", result.name, result.createdAt); 
}); 
0

schema.pre()フックがそれを行うだろう。例:彼らは独断回答やスパムを誘致する傾向があるよう

export const schema = new mongoose.Schema({ 
    name: String, 
    username: { 
     type: String, 
     required: true, 
     unique: true 
    }, 
    password: { 
     type: String, 
     required: true 
    } 
}, { timestamps: { createdAt: "created_at", updatedAt: "updated_at" } 
}); 

schema.pre("save", function (next) { 
    bcrypt.hash(this.password, 10, (err, hash) => { 
     this.password = hash; 
     next(); 
    }); 
}); 

schema.pre("update", function (next) { 
    bcrypt.hash(this.password, 10, (err, hash) => { 
     this.password = hash; 
     next(); 
    }); 
}); 
+0

そのスキーマのバルク操作のプレ/ポストフックもありますか? – phoebus

+0

[pre and post hooks](http://mongoosejs.com/docs/middleware.html)は、変更されたすべてのドキュメントに対して機能するので、バルク操作でも機能します。 コレクション全体を変更したい場合は、[migrate](https://www.npmjs.com/package/migrate)のようなものを探しているかもしれません。 –

+0

私の場合は移行する必要はありません。私は一括してオブジェクトをデータベースにアップアップしています。そして、その人が傷つけられるたびに、別の行動を引き起こしたい。 "save"と "update"を投稿し、他の多くのものはbulk.find()。upsert()。update()を使用したときに残念なことにトリガーされませんでした。 – phoebus

関連する問題