Expressアプリに「checked_in」フラグが付いた基本的なドキュメントがあります。
module.exports = Book= mongoose.model('Book', new Schema({
name : String,
checked_in : Boolean
},{ collection : 'Book' }));
書籍がチェックインおよびチェックアウトされたときのログを保持したかったので、別のスキーマを考え出しました。
var action = new Schema({
checked_in: Boolean,
});
module.exports = Activity = mongoose.model('Activity', new Schema({
book_id: String,
actions: [action]
},{ collection : 'Activity' }));
'book_id'は本のドキュメントIDである必要があり、本を更新するときは、アクション内の新しいアイテムでその本のアクティビティログを作成または更新する必要があります。
exports.update = function(req, res){
return Book.findById(req.params.id, function(err, book) {
var activity = new Activity({book_id: book.id});
activity.actions.push({
checked_in: req.body.checked_in,
});
Activity.update({ book_id: book.id}, activity.toObject(), { upsert: true }));
book.checked_in = req.body.checked_in;
return device.save(function(err) {
return res.send(book);
});
});
};
私が抱えている問題は、Activityコレクションに何も挿入されないことです。.save()を使用すると、コレクション内に多数の重複が発生します。
アップデート
私は以下のアドバイスで物事をやり直し始めましたが、まだこれで運がありません。これが私が今持っているものです:
module.exports = Activity = mongoose.model('Activity', new Schema({
book_id: Schema.ObjectId,
actions: [new Schema({
checked_in: Boolean,
last_user: String
})]
},{ collection : 'Activity' }));
更新コードは次のとおりです。
exports.update = function(req, res){
// TODO: Check for undefined.
return book.findById(req.params.id, function(err, book) {
if(!err) {
// Update the book.
book.checked_in = req.body.checked_in;
book.last_user = req.body.last_user;
book.save();
// If there's no associated activity for the book, create one.
// Otherwise update and push new activity to the actions array.
Activity.findById(book._id, function (err, activity) {
activity.actions.push({
checked_in: req.body.checked_in,
last_user: req.body.last_user
})
activity.save();
});
}
});
};
最終的には、誰かが本をチェックインまたはチェックアウトするたびに更新される一連のチェックアウト/インを含む各本のドキュメントです。すなわち:
{
book_id: "5058c5ddeeb0a3aa253cf9d4",
actions: [
{ checked_in: true, last_user: 'ralph' },
{ checked_in: true, last_user: 'gonzo' },
{ checked_in: true, last_user: 'animal' }
]
}
最終的には、各エントリ内にタイムスタンプがあります。