Last active
March 25, 2018 15:59
-
-
Save natanavra/abaf9a334e69d663a66952d8cb02297c to your computer and use it in GitHub Desktop.
Mongoose array setter/set not called on query
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const mongoose = require('mongoose'); | |
const Schema = mongoose.Schema; | |
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; | |
} | |
} | |
}); | |
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: 'first'}) | |
.then(console.log) | |
.catch(console.error); | |
})(); | |
//Output: | |
// "strings setter called" | |
// null | |
//Expected | |
// "strings setter called" | |
// "strings setter called" | |
// [Object] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment