使用猫鼬转换一系列文档 [英] Transform an array of documents using mongoose
问题描述
我正在运行一个特殊的查询,我想在此之后转换结果.
I am running a special query in which I want transform the results after.
User.find({}, function(err, users) {
// I want to remove/add some properties from/to each user here
});
有没有一种方法可以转换一系列文档?同样,这是一个特例,因此我不想对Schema进行转换,我认为该转换会像我想要的那样转换每个文档,但也会影响对User模型的所有其他查询.
Is there a way to transform an array of documents? Also this is a special case so I do not want to apply a transformation to the Schema, which I think would transform each document like I want, but would also affect all other queries to the User model.
基本上,我希望能够对返回的文档数组执行一次性转换.
Basically I want the ability to perform a one time transformation on the array of docs returned.
User.find({}, function(err, users) {
// I want to remove/add some properties to each user here
users.toJSON({transform: function(doc,ret,options) { /* do tranform*/ });
// That will not work as I get an error that toJSON is not defined for that
// array that was returned.
});
我可以通过在查询之前添加一个转换,然后在查询完成后删除该转换来伪造它,但这是非常糟糕的hack恕我直言.
I might be able to fake it out by adding a transformation right before I query and then removing that transformation when the query is complete, but that is a pretty bad hack IMHO.
想法?我是否错过了文档中的某些内容?
Ideas? Did I miss something in the docs?
推荐答案
您可以使用 lean
查询,以便从查询中返回纯JS对象数组,然后使用
You can use a lean
query so that an array of plain JS objects are returned from the query and then use map
to transform the array:
User.find({}).lean().exec(err, users) {
users = users.map(function(user) {
// transform user into newuser as needed.
...
return newuser;
});
});
这篇关于使用猫鼬转换一系列文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!