简体   繁体   中英

Best practice to create/update Mongoose objects

I have some multi depth Mongoose schemas. When creating/updating I currently assign each provided value from a json object to the object field. However I would like to do a couple of things. For one I would like to auto remove null values to prevent Mongoose from trying to validate them and second I would like to not assign each value/field individually but pass it the whole json object and have the schema handle the validation using that - I assume that if there are extra/non existent fields in the json object they will just be discarded. My solution is to therefore create a function that will recursively walk through the json object removing both null values as well as forbidden fields (ie created_at, _id, etc) then just pass the rest along and save. Does anyone have a suggestion for something in Mongoose that already does that or of there are an issues I am not seeing with this approach?

Maybe this method is what you want findByIdAndUpdate

In fact, when you use save() method, it only update the field you changed:

result.true_name = "test233334";
result.save();

The Log: Mongoose: admins.update({ _id: ObjectId("51b5af1a370c3fa716000001") }) { '$set': { true_name: 'test233334', updated_at: new Date("Mon, 10 Jun 2013 10:49:38 GMT") } } {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM