Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I $addToSet and upsert an array?

I'm using Mongoose and my Schema looks like:

var WalletSchema = new Schema({
  accounts: [String]
});

My query (Node.js) looks like:

Wallet.update {accounts: account}, {$addToSet: {accounts: account}}, {upsert: true}, (err, updWallet) ->
  asyncCb err

However, I don't have any wallets in my database and I expected this to upsert. It does not. Instead it returns an error: MongoError: Cannot apply $addToSet modifier to non-array

Am I doing something wrong?

like image 841
Shamoon Avatar asked Jan 12 '14 03:01

Shamoon


2 Answers

This Behavior is now supported by Mongodb 3.2

From MongoDB documentation: If the field is absent in the document to update, $addToSet creates the array field with the specified value as its element.

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

like image 142
rat Avatar answered Sep 22 '22 18:09

rat


You either have to initialize your account document with an empty accounts array on first creation or use $push if your first $addToSet fails. $push creates a new field if the field is absent, which $addToSet does not.

like image 25
heinob Avatar answered Sep 21 '22 18:09

heinob