【发布时间】:2012-09-30 18:50:48
【问题描述】:
我的快递应用中有一个带有“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' }
]
}
最终我将在每个条目中都有一个时间戳。
【问题讨论】:
-
在您的代码更新后,您需要帮助解决哪些具体问题?
-
它不会创建新的活动,可能是因为我使用的是 findById。但如果我只使用 .save() ,我最终会得到很多相同书籍 ID 的重复文档。
标签: javascript node.js mongodb express mongoose