2

I am trying to update a MongoDB collection that I have created a schema for using Mongoose. My goal is to remove all elements in an array known as 'alarms' that are less than (in the past) of the current time.

Here is my Mongoose Schema:

var mongoose = require('mongoose');

var ReminderSchema = new mongoose.Schema({
    firstName: String,
    lastName: String,
    phone: Number,
    email: String,
    medication: String,
    alarms: [Date]
});

module.exports = mongoose.model('Reminder', ReminderSchema); 

Here is the update. I am trying to remove all alarms that are less than the current date.

var date = new Date();
var Reminder = require('./models/Reminders.js');

//remove ALL alarms that are are before current time
Reminder.update({alarms: {$lte: date}}, {$pullAll: {alarms: {$lte: date}}}, function(err, updated){
    if(err){
         console.log(err);
     }
     else {
         console.log(updated);
     }
 });

I am currently getting this error:

{ [MongoError: $pullAll requires an array argument but was given a Object]
name: 'MongoError',
message: '$pullAll requires an array argument but was given a Object',
driver: true,
index: 0,
code: 2,
errmsg: '$pullAll requires an array argument but was given a Object' }

Any thoughts?

2
  • 1
    Just replace the $pullAll by $pull Commented Jan 26, 2016 at 18:22
  • This works. Thank you. Commented Jan 26, 2016 at 18:31

1 Answer 1

2

The $pullAll receives an array not an object:

{ $pullAll: { <field1>: [ <value1>, <value2> ... ], ... } }

The $pullAll operator removes all instances of the specified values from an existing array. Unlike the $pull operator that removes elements by specifying a query, $pullAll removes elements that match the listed values.

the solution you should use $pull :

Reminder.update({alarms: {$lte: date}},{$pull:{alarms: { $lte : new Date()}}}, 
 function(err, updated){
if(err){
     console.log(err);
 }
 else {
     console.log(updated);
 }
});

https://docs.mongodb.org/manual/reference/operator/update/pullAll/

Sign up to request clarification or add additional context in comments.

1 Comment

This does the job. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.