When a new user prompts the MPOS & amp; Before saving the MongoDB user frequency, I want to get the values from another collection. Currently I use the following solution, but it causes the user to save twice ... Worse, if the user does not pass verification first, then the save ()
is said anyway. Usually an unwanted exception is generated.
My current code works in the following ways:
UserSchema.path ('address.postCode'). Set (function (newVal), cb) {var that = this; This.model ('PostCode'). FindOne ({postCode: newVal}, function (mistake, postcode) {if (postCode) {that.longitude = postCode.longitude; that.latitude = Postcode.latitude;} and {that.longitude = undefined; that.latitude = undefined ;} That.save ();}); Return newVal;});
Anyone knows the better way to do this?
The function is expected to have a synchronous return, you have an asynchronous call inside this function and therefore < Code> Back will be named after PostCode
Also, you should not call save
inside the setter Save as it will be saved anyway.
Since you want to get data from another model, you should use pre-middleware, for example:
UserSchema.pre ('save', true, Function (next, done) {var that = this; if (this.isNew || this.isModified ('address.postCode')) {This.model ('PostCode'). FindOne ({postCode: that.address.postCode }, Function (mistake, postcode) {if (postCode) {that.longitude = postCode.longitude; that.latitude = postCode .latitude;} and {that.longitude = undefined; that.latitude = undefined;} done (); });} next ();}); The second parameter has been passed for
pre
( true
), it defines that it is an asynchronous middleware.
For more information on mediators, check.
No comments:
Post a Comment