Last active
March 25, 2018 16:00
-
-
Save natanavra/bde432a4f54fc6e7b44961d0ba30c08b to your computer and use it in GitHub Desktop.
Mongoose primitive set/setter is called twice when running a 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({ | |
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