3

I have an array of mongoose queries like so

var q = [{"_id":'5324b341a3a9d30000ee310c'},{$addToSet:{"Campaigns":'532365acfc07f60000200ae9'}}]

and I would like to apply them to a mongoose method like so

var q = [{"_id":'5324b341a3a9d30000ee310c'},{$addToSet:{"Campaigns":'532365acfc07f60000200ae9'}}]

Account.update.apply(this, q);

How can I do this ? How can I convert an array of mongoose query objects to mongoose parameters?

I tried the following but it doesnt work.

    var q = [{
        "_id": '5324b341a3a9d30000ee310c'
    }, {
        $addToSet: {
            "Campaigns": '532365acfc07f60000200ae9'
        }
    }]

    Account.update(q).exec(function (e, r) {
        console.log(r)
        console.log('ERROR')
        console.log(e)
        console.log('ERROR')
        cb(e, r);
    });

3
  • Why not just pass the two params? Commented Mar 16, 2014 at 2:24
  • Because the Im getting the array from the functions arguments parameter. function(){ var args = Array.prototype.slice.call(arguments, 0);} Commented Mar 16, 2014 at 4:19
  • OK -- I added the answer that shows you how to make apply work correctly. Commented Mar 16, 2014 at 14:09

2 Answers 2

1

All you need to do is pass in the correct object context via apply to the update method:

Account.update.apply(Account, q)
    .exec(function(e, r) {
    // your code here ...
});

The this needs to be the Model instance, not the global scope context (or whatever else this may have been at the time it was called).

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

Comments

0

Basically seems to be just the way the prototype of the function seems to be passed in. So if you want to build your arguments dynamically then you need to do something like this:

var q = [
  { "_id": account._id },
  { "$addToSet": { "Campaigns": campaign._id } },
];

Account.update( q[0], q[1], (q[2]) ? q[2] : {}, function(err, num) {

Essentially then you are always passing in the query, update and options documents as arguments. This uses the ternary condition to put an empty {} document in as the options parameter, where it does not exist in your dynamic entry.

4 Comments

Yes, that seems to be the best way to do it. Thanks!
The context passed to apply was incorrect. See my answer.
@WiredPrairie It cannot be incorrect when I have tested it and it works. Perhaps you misread the response.
The this context in the original question I meant. Not your answer. Yours works too.

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.