如何让数组过滤器适用于Mongoose? Nodejs,Mongoose,哈巴狗

时间:2018-04-07 17:15:05

标签: node.js mongodb mongoose pug

**更新:因为Mongoose支持数组过滤器而无法正常工作,有人可以找出如何使用Mongoose支持的东西来实现这一点,比如$ project或$ group或者其他东西吗?

我想要发生什么: 将“records”数组中的每个“used”字段设置为 true (如果已经设置为false)。

我的收藏如下:

{room: 209, 
 school: "Lime Vernon HS", 
 records:[
       {date:'3/24/2018',
        lesson:'Treble Clef', 
        game:'Trebleball', 
        used:false,
        cancel:false
       }, 
       {
         date:'3/24/2018', 
         lesson:'Treble Clef', 
         game:'Trebleball', 
         used:false, 
         cancel:false
       }, 
       {
         date:'3/24/2018', 
         lesson:'', game:'', 
         used:true, 
         cancel:true
       }, 
       {
         date:'3/24/2018', 
         lesson:'Treble Clef', 
         game:'Trebleball', 
         used:false, 
         cancel:false
      }]

以下是我使用的代码:

Hook.updateMany({ room:209}, { $set: { "records.$[elem].used" : true } },
{ arrayFilters: [ { "elem.used": false } ] }, function(err){

    if(err){
        console.log(err);
    }
    else{
        return res.redirect("/home")
    }

})

结果:没有发生任何事情,我的收藏看起来仍然完全一样,就像我什么都没做。

我想要的结果(“used”字段设置为true):

{room: 209, 
 school: "Lime Vernon HS", 
 records:[
       {date:'3/24/2018',
        lesson:'Treble Clef', 
        game:'Trebleball', 
        used: true,
        cancel:false
       }, 
       {
         date:'3/24/2018', 
         lesson:'Treble Clef', 
         game:'Trebleball', 
         used: true, 
         cancel:false
       }, 
       {
         date:'3/24/2018', 
         lesson:'', game:'', 
         used:true, 
         cancel:true
       }, 
       {
         date:'3/24/2018', 
         lesson:'Treble Clef', 
         game:'Trebleball', 
         used: true, 
         cancel:false
      }]

这是我的架构:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var uniqueValidator = require('mongoose-unique-validator');

var HookSchema = new mongoose.Schema({
room:{
    type:Number,
    required:true
},
classPoints:{
    type:Number,
    default:0
},
uanns: [Announcement], 
newHires: [Workers],
firstlights:[Award],
octlights:[Award],
novlights:[Award],
declights:[Award],
janlights:[Award],
feblights:[Award],
marlights:[Award],
aprlights:[Award],
maylights:[Award],
junlights:[Award],
eon:[AwardB],
milestone:[AwardB],
legend:[AwardB],
eonNominees:[Nominee],
reservedAvatars:[Reserved],
records:[Record]

});

1 个答案:

答案 0 :(得分:0)

    Hook.find({room:209}).arrayFilters( [ { "elem.used": false } ] )
   .updateMany( { $set: { "records.$[elem].used" : true } } );

请试试这个,首先过滤:)。