Skip to content

Instantly share code, notes, and snippets.

@natanavra
Last active March 25, 2018 16:00
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/bde432a4f54fc6e7b44961d0ba30c08b to your computer and use it in GitHub Desktop.
Save natanavra/bde432a4f54fc6e7b44961d0ba30c08b to your computer and use it in GitHub Desktop.
Mongoose primitive set/setter is called twice when running a query
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const schema = new Schema({
item: {
type: String,
set: function(item) {
console.log('item setter called')
return normalize(item);
}
}
});
const Model = mongoose.model('Object', schema);
function normalize(url) {
return url.substr(0, url.length - 1);
}
(function main() {
const item = new Model({item: 'item'});
item.save();
Model.findOne({item: 'item'})
.then(console.log)
.catch(console.error)
})();
//Output:
// "item setter called" (save)
// "item setter called"
// "item setter called"
// null
//Expected:
// "item setter called" (save)
// "item setter called" (find)
// [Object]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment