Domanda

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?

È stato utile?

Soluzione 2

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.

Altri suggerimenti

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/

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top