简体   繁体   中英

I want to query with elemmatch

My mongoose schema for example:

const newwant = new mongoose.Schema({
  statuscol : {
    type : Boolean,
    default : false,
    required :true
  }
})


   const Rooms = new mongoose.Schema({
  createdBy : {
    type : String,
    required : true
  },
  Roomname : {
    type : String,
    required : true
  },
  createdDate : {
    type : Date,
    default : Date.now
  },
  Message : [{
    username : String,
    date :  Date
  }],
  wants : [newwant]
})

An api I wrote with express will be added and the false value can be returned to true. What I want to do now is to freeze only objects whose value is in the wants array.

I tried such a code for this but it didn't work

     router.get("/accepted",async(req,res) => {
    try{ 
  rooms.findById(req.body.id,{wants : {$elemMatch : {"statuscol" : true}}},
      function(err, result) {
        if (err) {
          res.send(err);
        } else {
          res.json(result);
        }
      }
        ) 
    }catch(err){
      console.log(err)
    }
  })

When I run this code, even though there is 2 true in the collection, it only freezes one object so it doesn't work for me, I will be glad if you help, you can ask if you have any questions.

"mongoose": "^5.12.2"

findById() triggers findOne() middleware. So, use find( {_id: req.body.id} ) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM