Skip to content

Instantly share code, notes, and snippets.

@natanavra
Last active March 25, 2018 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natanavra/abaf9a334e69d663a66952d8cb02297c to your computer and use it in GitHub Desktop.
Save natanavra/abaf9a334e69d663a66952d8cb02297c to your computer and use it in GitHub Desktop.
Mongoose array setter/set not called on query
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