Search code examples
node.jsmongodbmongoosemongoose-schemamongoose-populate

It is possible to pull elements from a referred objects' array using mongoose?


I have 2 mongo schemas related one with the other using ObjectId:

var User = new Schema({
    username: {
      type:String,
      unique: true
    },
    password: { 
        type:String
    },
    verified:   {
        type: Boolean,
        default: false
    },
    lastActivity:{
      type:Date,
      default:Date.now
    }
});

And a watitingRoom schema with lists all the users:

var WaitingRoom = new Schema({
    lastActivity:{
          type:Date,
          default:Date.now
    },
    clients: [{
        type : mongoose.Schema.ObjectId,
        ref: 'User'
    }],
    videocalls: [{
        type: mongoose.Schema.ObjectId,
        ref:'VideoCall'
    }]
});

So, I want to 'refresh' my clients array pulling all the clients which a lastActivity less than the current time. I tried it by using the $pull tool present in mongoose. After googling and mixing different examples I tried things like:

WaitingRoom.findOneAndUpdate({}, { lastActivity: new Date(),
                                      $pull : {clients : {"clients.lastActivity": { $lt: new Date() }}}
                                     }, options)
    .populate("clients")
    .exec( function(error, waitingRoom) {
            if (err) { return res.status(500).send({ msg: err.message }); }

    })

Which finds the unique waiting room, updates the lastActivity field and tries to pull all the clients that has a clients.lastActivity less than the current date.

(Obviously this snipped code doesn't work)

The problem is that I didn't find any documentation or example that explains if it is possible to pull elements from a referred ObjectId schema using a nested condition clients.lastActivity


Solution

  • You need to first find the ids from User database and then need to $pull them from the WaitingRoom database

    User.find({ lastActivity: new Date() }).then((users) => {
      const ids = []
      users.map((user) => {
        ids.push(user._id)
      })
      WaitingRoom.update({}, { $pull: { clients: ids }}, { multi: true }).then(() => {
        console.log('removed')
      })
    })