私のスキーマのような削除に問題がある
/**
* Article Schema
*/
var Comments = new Schema({
body: { type : String, default : '' },
user: { type : Schema.ObjectId, ref : 'User' },
createdAt: { type : Date, default : Date.now }
})
var Likes = new Schema({
user: { type : Schema.ObjectId, ref : 'User' },
createdAt: { type : Date, default : Date.now }
})
var ArticleSchema = new Schema({
title: {type : String, default : '', trim : true},
body: {type : String, default : '', trim : true},
geo: {type: [Number], set: setTags},
user: {type : Schema.ObjectId, ref : 'User'},
comments: [Comments],
likes: [Likes],
tags: {type: [], get: getTags, set: setTags},
image: {type:String, default : ''},
createdAt : {type : Date, default : Date.now}
})
そして、好きな/好きではない機能を作りたいです。好きなものを追加しても、削除してもドキュメントは変更されません。コントローラ:
exports.like = function (req, res) {
var article = req.article
var user = req.user
Article.getArticleByWithLikesByUserId(req.user.id, function(err, articles) {
console.log(articles);
if(!articles.length){
console.log('adding like',new Date);
article.addLike(user, function (err) {
if (err) return res.render('500')
res.redirect('/articles/'+ article.id)
});
}
else{
console.log('removing like',new Date);
article.removeLike(user, function (err) {
if (err) return res.render('500')
res.redirect('/articles/'+ article.id)
});
}
});
スキーマ メソッド:
addLike: function (user, cb){
this.likes.push({
user: user._id
})
this.save(cb);
},
removeLike: function (user, cb){
var that = this;
this.likes.forEach(function(like, index) {
if(like.user == user.id){
var newLikesObj = that.likes.toObject();
console.log("before splice:\n ",newLikesObj);
newLikesObj.splice(index,1);
console.log("after splice: \n",newLikesObj);
that.likes = newLikesObj;
that.save(cb)
}
});
ログから、スプライスは正常に機能しているようです
before splice:
[ { user: 5247095b5696e45c2b000102,
_id: 524defc87153550829000103,
createdAt: Fri Oct 04 2013 01:29:28 GMT+0300 (Финляндия (лето)) },
{ user: 5247095b5696e45c2b000002,
_id: 524df3c2a663050805000003,
createdAt: Fri Oct 04 2013 01:46:26 GMT+0300 (Финляндия (лето)) } ]
after splice:
[ { user: 5247095b5696e45c2b000102,
_id: 524defc87153550829000103,
createdAt: Fri Oct 04 2013 01:29:28 GMT+0300 (Финляндия (лето)) } ]
静的メソッド:
getArticleByWithLikesByUserId: function (id, cb) {
this.find({ 'likes.user' : id })
.populate('user', 'name email username')
.populate('comments.user')
.exec(cb)
}
私もこの更新方法を試しましたが、numberAffected が 1 を示していても、まだ削除されません。
this.update({$pull : {'likes.user':user.id}}, function(err, numberAffected){
if(!err){
return console.log('like removed');
} else {
return console.log(err);
}
});