我有一个“checked_in”标志的基本文件在我的快递应用Upserting文件:猫鼬与嵌套模型
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);
});
});
};
我遇到的问题是什么都没有插入到活动集合中。如果我使用.save(),那么我只是在集合中获取大量重复项。
UPDATE
我已经开始重新工作的事情与下面给出的意见,但我仍然没有任何这方面的运气。这是我现在有:
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' }
]
}
最终我会在每个条目中有一个时间戳。
代码更新后,有什么特别不工作,你需要哪些帮助? – JohnnyHK
它不会创建新的活动,可能是因为我在使用findById。但是,如果我只是使用.save(),我最终会得到大量相同书目ID的重复文档。 – backdesk
“upserting”是什么意思? – chovy