我正在使用MongoDB和Node.JS开发一个upvoting / downvoting应用程序 我创建了两个相互关联的模式:
var mongoose = require('mongoose');
var Voters = require('./voters');
var PostSchema = new mongoose.Schema({
title: String,
link: String,
upvotes: {type: Number, default: 0},
voters: [Voters.schema],
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
});
mongoose.model('Post', PostSchema);
和选民:
var mongoose = require('mongoose');
var votersSchema = new mongoose.Schema({
voter_id: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
votetype: Number
});
module.exports = mongoose.model('Voters', votersSchema);
为了在选民阵列中包含用户,我使用此代码:
var voterModel = new Voters();
voterModel.voter_id = req.payload._id;
voterModel.votetype = 1;
foundPost.voters.push(voterModel);
foundPost.save();
哪种方法效果很好。为了删除用户,我尝试了几种方法,但似乎都没有。目前的是$ pull:
foundPost.update({'voters.voter_id': req.payload._id}, {$pull: {'voters': {'voter_id': req.payload._id, 'votetype': 1}}}, function(err){
if (err) { console.log(err); }
});
更新操作在mongo shell中有效,但不在节点内。我也尝试过foundPost.voters.remove,但结果是一样的。还尝试了Voters.findOne,但查询始终返回null。
任何帮助都将不胜感激。
答案 0 :(得分:0)
首先使用id
方法查找选民,然后将其删除,最后保存文档以应用更改:
var voter = foundPost.voters.id(req.payload._id).remove();
foundPost.save(function (err) {
if (err) return handleError(err);
console.log('the voter was removed')
});