简体   繁体   English

模式方法不适用于mongodb中的find方法

[英]schema methods doesn't work with find method in mongodb

I created a schema.methods.toAuthJSON which will return filtered data. 我创建了一个schema.methods.toAuthJSON ,它将返回过滤后的数据。 while i use findOne() it works just fine. 虽然我使用findOne()正常工作。 but When I use just find() it doesn't work. 但是当我只使用find()它不起作用。 how should i get it right? 我应该如何正确处理?

Member.findOne().exec((err, member) => {

res.json(member.toAuthJSON())
})

The question definitely needs more detail but IF we assume as stated that the shown findOne code works but the not shown find code does not, then it is probably due to the return value not being used correctly for the find code. 这个问题肯定需要更多细节,但是如果我们假设陈述的那样,所示的findOne代码可以工作,但未显示的find代码不能工作,则可能是由于返回值未正确地用于find代码。

Assumption for missing find code: 缺少find代码的假设:

Member.find().exec((err, member) => {
  res.json(member.toAuthJSON())
});

Again, if this assumption is correct then it is a misunderstanding of the returned value from find . 同样,如果这个假设是正确的,那就是对find返回值的误解。 While findOne will return a single document, find returns an array of documents. findOne将返回单个文档,而find将返回一个文档数组 So the assumed code would need to be updated to iterate over the returned array invoking the custom method for each document. 因此,需要更新假定的代码以遍历返回的数组,从而为每个文档调用自定义方法。

One approach would be to use a map: 一种方法是使用地图:

Member.find().exec((err, members) => {
  res.json(members.map((member) => member.toAuthJSON()));
});

This approach will map over the returned array of documents returning a new array of outputs from the custom method. 此方法将映射在返回的文档数组上,并从custom方法返回新的输出数组。

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

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