从属于子文档数组的子文档中提取
问题描述:
我正在开发类QA项目。从属于子文档数组的子文档中提取
我的问题,目前的模式是这样的:
var questionSchema = new mongoose.Schema({
content: String,
answers: [{
content:String,
.
.
.
votes: [{
type: mongoose.Schema.ObjectId,
ref: 'User'
}]
}]
});
由于每个用户都有权每个问题超过1票,我想$pull
所有的用户在一个投票支持票对使用Model#update
的事件提出质疑。
下面是我的代码:
Event.update({_id: req.params.id}, {$pull: {'answers.votes': req.user.id}}).execAsync()
.catch(err => {
handleError(res, err);
}).then(num => {
if(num === 0) { return res.send(404).end(); }
}).then(() => {exports.show(req,res);});
但是我收到的“不能使用的部分(..)横贯元件”的错误。
我查询/更新不正确?
答
{$pull: {'answers.votes': req.user.id}}
不是使用$pull
的正确方法,而是使用{$pull: {answers:{votes: req.user.id}}}
代替。
试试下面的代码: -
Event.update({_id: req.params.id}, {$pull: {answers:{votes: req.user.id}}}).execAsync()
.catch(err =>
{
handleError(res, err);
}).then(num =>
{
if(num === 0)
{ return res.send(404).end(); }
}).then(() => {exports.show(req,res);});
参考$pull-doc知道如何使用它。
希望这会帮助你。
它很好用!谢谢!我想我仍然对运营商的使用感到困惑。但我会更多地查看它。再次感谢! –