mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

Setters not running on array types on query?

Open natanavra opened this issue 8 years ago • 19 comments

Do you want to request a feature or report a bug? bug

What is the current behavior? Array setter function not called on find query

If the current behavior is a bug, please provide the steps to reproduce. https://gist.github.com/natanavra/abaf9a334e69d663a66952d8cb02297c

What is the expected behavior? The array setter should be called when running a query.

Please mention your node.js, mongoose and MongoDB version. Node 9.6.1 Mongo 3.4.0

natanavra avatar Mar 25 '18 15:03 natanavra

It does appear that the array setter does not run on query.

@natanavra I edited your example slightly so the query would find a matching doc:

const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/test')
const Schema = mongoose.Schema

const schema = new Schema({
  strings: {
    type: [String],
    default: () => void 0,
    required: true,
    set: function (items) {
      console.log('array of strings setter called')
      for (let i = 0; i < items.length; i++) {
        items[i] = normalize(items[i])
      }
      return items
    }
  }
})

const Model = mongoose.model('Object', schema)

function normalize (url) {
  return url.substr(0, url.length - 1)
}

function main () {
  const item = new Model({ strings: ['first', 'second', 'third'] })
  item.save()

  Model.findOne({ strings: 'firs' }) // (removed t) when saved initially, array values are truncated.
    .then(console.log)
    .catch(console.error)
}
main()

output:

issues: node ./6277.js
array of strings setter called
{ _id: 5ab8e0a2cb3079773ae9aa8d,
  strings: [ 'firs', 'secon', 'thir' ],
  __v: 0 }
^C
issues: 

[EDIT] I'm assuming you're using mongoose5@latest since you're not declaring runSettersOnQuery the way you had to in mongoose@4.

ghost avatar Mar 26 '18 12:03 ghost

the setter also does not run if you actually update the value of the array:

async function main () {
  const item = new Model({ strings: ['first', 'second', 'third'] })
  await item.save()

  Model.findOneAndUpdate({ strings: 'firs' }, { strings: ['wxyz', 'abcd'] }, { new: true })
    .then(console.log)
    .catch(console.error)
}
main()

output:

issues: node ./6277.js
array of strings setter called
{ _id: 5ab8e0a94c372077437511d2,
  strings: [ 'wxyz', 'abcd' ],
  __v: 0 }
^C
issues: 

however, if you update the returned document and subsequently save it, the setter is called:

async function main () {
  await Model.remove({})
  await item.save()

  let doc = await Model.findOne({ strings: 'firs' })
  doc.strings.push('AAA', 'BBB')
  let saved = await doc.save()
  console.log(saved)
  return mongoose.connection.close()
}

output:

issues: node ./6277.js
array of strings setter called
array of strings setter called
{ _id: 5ab8eb097cdfb17df4ec1829,
  strings: [ 'firs', 'secon', 'thir', 'AA', 'BB' ],
  __v: 1 }
issues: 

ghost avatar Mar 26 '18 12:03 ghost

I meant I was expecting the setter to run on the query object, so the 't' would be removed by the setter. This does happen with primitive fields setter. The behaviour is not documented and I'm not sure what to expect.

Additionally, retrieving the object and making the modifications, is two queries, which is redundant. I expect the setter to run on the query object.

natanavra avatar Mar 26 '18 14:03 natanavra

@natanavra I agreed with you in my first comment that the setter for the array path is not running on query.

Here is an example that codifies the expectation that setters on arrays should behave the same on queries as string setters do ( but they don't):

6277.js

'use strict'

const assert = require('assert')
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/test')
const Schema = mongoose.Schema

var s = 0
var a = 0

const schema = new Schema({
  name: {
    type: String,
    set: function (str) {
      s++
      return str
    }
  },
  strings: {
    type: [String],
    default: () => void 0,
    required: true,
    set: function (items) {
      a++
      return items
    }
  }
})

const Model = mongoose.model('Object', schema)

const item = new Model({
  name: 'Mark',
  strings: ['first', 'second', 'third']
})

async function main () {
  await Model.remove({})
  await item.save()

  let doc = await Model.findOne({ strings: 'first' })
  await Model.findOne({ name: 'Mark' })

  assert.equal(doc.name, 'Mark')
  assert.equal(s, 2, 'String setter not called twice')
  assert.equal(a, 2, 'Array of Strings setter not called twice')

  return mongoose.connection.close()
}

main().catch(e => {
  console.error(e)
  return mongoose.connection.close()
})

Output:

issues: node ./6277.js 
{ AssertionError [ERR_ASSERTION]: Array of Strings setter not called twice
    at main (/Users/lineus/dev/Help/mongoose5/issues/6277.js:46:10)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
  generatedMessage: false,
  name: 'AssertionError [ERR_ASSERTION]',
  code: 'ERR_ASSERTION',
  actual: 1,
  expected: 2,
  operator: '==' }
issues: 

My second comment was just me trying to understand the problem space and I should have just kept it in a private note to myself. It wasn't meant as a suggestion for what you should be doing.

ghost avatar Mar 27 '18 09:03 ghost

@lineus Sorry, I misinterpreted your comments, looked at the modified code example (which does return the desired output, but the original was written that way on purpose to show that if the setter would have executed, we would get the desired output). Thanks for the elaborate response.

natanavra avatar Mar 27 '18 09:03 natanavra

That's my fault, I wasn't clear about the purpose of the comment :)

I was also totally wrong about the query not returning a result because of the condition in the findOne({ strings: 'first' }). I tried to read everything I could about setters/getters, but I misunderstood that the setter would effect the condition before the query gets sent. Which in hindsight is silly :)

ghost avatar Mar 27 '18 10:03 ghost

I've narroed the problem down. The one time the setter runs is because of the save operation i believe. SO it does look like setters are not being run in find operations on array fields:

'use strict'

const assert = require('assert')
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/test')
const Schema = mongoose.Schema

var s = 0
var a = 0

const schema = new Schema({
  name: {
    type: String,
    set: function (str) {
      s++
      return str
    }
  },
  strings: {
    type: [String],
    default: () => void 0,
    required: true,
    set: function (items) {
      console.log('running')
      a++
      return items
    }
  }
})

const Model = mongoose.model('Object', schema)

const item = new Model({
  name: 'Mark',
  strings: ['first', 'second', 'third']
})

async function main () {
  await Model.remove({})
  await item.save()

  console.log('a before finds', a);
  let doc = await Model.findOne({ strings: 'first' })
  let doc2 = await Model.findOne({ strings: 'secon' })

  assert.equal(doc.name, 'Mark')
  console.log('a', a)
  assert.equal(a, 2, 'Array of Strings setter not called twice')

  return mongoose.connection.close()
}

main().catch(e => {
  console.error(e)
  return mongoose.connection.close()
})

sobafuchs avatar Mar 27 '18 20:03 sobafuchs

just a quick update:

the value of this in this.setters in SchemaType.prototype._applySetters() during the query operation is SchemaString, so it's not magically picking the correct SchemaType based on the schema, but more than likely picking it based on the condition type in the query. Trying to sort this out now.

ghost avatar Apr 01 '18 14:04 ghost

As a workaround, instead of this:

const schema = new Schema({
    strings: {
        type: [String],
        default: () => void 0,
        required: true,
        set: function(items) {
            console.log('strings setter called');
            for(let i = 0 ; i < items.length ; i ++) {
                items[i] = normalize(items[i]);
            }
            return items;
        }
    }
});

Do this:

const schema = new Schema({
    strings: {
        type: [{
          type: String,
          set: normalize
        }],
        default: () => void 0,
        required: true
    }
});

Should be equivalent for most cases and I can confirm this setter will run in mongoose 5.0.12.

vkarpov15 avatar Apr 02 '18 01:04 vkarpov15

Upon closer inspection I'm going to have to chalk this up to expected behavior. Sorry for the inconvenience, but the workaround I mentioned is the right way to go about this. This change would likely be backwards breaking and also break the contract that a setter on a given schematype runs when we're actually casting a value to that schematype.

vkarpov15 avatar Apr 03 '18 00:04 vkarpov15

How is that expected behaviour? Can you point me in the direction? Since the documentation is rather vague about Setters to begin with. This makes finding bugs very difficult, I'm not sure when mongoose does magic and when not...

natanavra avatar Apr 03 '18 10:04 natanavra

What do you mean by "can you point me in the direction"?

vkarpov15 avatar Apr 03 '18 22:04 vkarpov15

Can you point me to where this is documented as the expected behavior, and to the details describing the expected behavior

natanavra avatar Apr 04 '18 07:04 natanavra

@vkarpov15 Your work around is an elegant solution in the use case described above, but what would be your recommended way to go in case the setter is supposed to transform the array globally? Like in this example:

const schema = new Schema({
    numbers: {
        type: [Number],
        set: items => items.sort((a, b) => a - b),
    }
});

BrunoGodefroy avatar Apr 04 '18 09:04 BrunoGodefroy

@BrunoGodefroy if your query is MyModel.find({ numbers: 2 }) there is no array to transform, just a single isolated value. However, you are right that the setter won't run if you do MyModel.find({ numbers: [2] }), that's a problem that we need to fix.

vkarpov15 avatar Apr 11 '18 16:04 vkarpov15

{ _id:13213 name:'test', demo:[{ name:'test', is_active:true, },{ name:'test1', is_active:false, }] } db.User.find({"_id": '13213',"demo.is_active": true}); db.User.find({"_id": '13213',demo: {"$elemMatch": {is_active: true}});

both queries are not working

Vishal23016 avatar May 02 '19 05:05 Vishal23016

@Vishal23016 can you please clarify what you mean by "not working", what output are you getting and what output do you expect?

vkarpov15 avatar May 06 '19 17:05 vkarpov15

i try find array of object is_active key only true

ex :[{name:'test',is_active:true},{name:'test1',is_active:true},{name:'test',is_active:false}]

need to out only true array of object

On Mon, May 6, 2019 at 10:41 PM Valeri Karpov [email protected] wrote:

@Vishal23016 https://github.com/Vishal23016 can you please clarify what you mean by "not working", what output are you getting and what output do you expect?

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/Automattic/mongoose/issues/6277#issuecomment-489697933, or mute the thread https://github.com/notifications/unsubscribe-auth/ALOAA7JNQUQNDHLXT6YIYJDPUBRC5ANCNFSM4EXIYQJA .

Vishal23016 avatar May 07 '19 05:05 Vishal23016

Do you mean you're trying to filter out all elements of the array where is_active = false?

vkarpov15 avatar May 11 '19 21:05 vkarpov15