简体   繁体   English

创建/更新猫鼬对象的最佳实践

[英]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. 当创建/更新时,我目前将每个提供的值从json对象分配给object字段。 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. 对于一个我想自动删除空值以防止Mongoose尝试验证它们,第二个我不希望不单独分配每个值/字段,而是将整个json对象传递给它,并让架构使用该值处理验证-我假设如果json对象中有多余/不存在的字段,它们将被丢弃。 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. 因此,我的解决方案是创建一个函数,该函数将递归遍历json对象,同时删除null值和禁止字段(即created_at,_id等),然后将其余部分传递并保存。 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 也许这个方法就是你想要的findByIdAndUpdate

In fact, when you use save() method, it only update the field you changed: 实际上,当您使用save()方法时,它只会更新您更改的字段:

result.true_name = "test233334"; result.true_name =“ test233334”;
result.save(); 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") } } {} 日志: Mongoose: admins.update({ _id: ObjectId("51b5af1a370c3fa716000001") }) { '$set': { true_name: 'test233334', updated_at: new Date("Mon, 10 Jun 2013 10:49:38 GMT") } } {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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