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?
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With