在发布文档之前,如何在find()中修改对象级别的文档
How can I modify the documents on an object-level in find() before I publish them?
我想在发布方法中修改find()游标中匹配的文档。但是,它不应该保存到Mongo中。
示例:
Email.find({})返回的文档如下{电子邮件:"hello@hello.com"},它与Mongo收藏中的一个记录相匹配。
但我想做一个额外的步骤,那就是检查电子邮件是否经过验证(可能在另一个集合中,或者一些逻辑过程中,并像这样附加它。
也就是说,我想发布
{电子邮件:"hello@hello.com",is_verified:true}
而Mongo中的文档仍然{email:"hello@hello.com"}
我该怎么做?谢谢
var Docs = new Meteor.Collection('docs', {
transform: function(doc) {
...
return anythingYouWant;
},
});
或
var docs = Docs.find({...}, {
transform: function(doc) {
...
return anythingYouWant;
},
});
请参阅http://docs.meteor.com/#meteor_collection和http://docs.meteor.com/#find。
如Meteor文档中所述,如果您仔细阅读,transform
不是所问问题的正确解决方案:
文档在返回之前将通过此功能传递从fetch或findOne,并且在传递给的回调之前observe、map、forEach、allow和deny对于observeChanges的回调或从发布返回的游标功能
转换出版物中文档的正确解决方案是使用类似maximum:servertransform:的包
$ meteor add maximum:server-transform
Meteor.publishTransformed('allDocsTransformed', function() {
return Docs.find().serverTransform({
extraField: function(doc) {
// use fields from doc if you need to
return 'whatever';
}
});
});
或者DIY通过编写自定义出版物来实现相同的功能,在该出版物中,您可以与观察者一起处理文档流,如下所示:
function transform(doc) {
doc.extraField = 'whatever';
return doc;
}
Meteor.publish('allDocsTransformed', function() {
const observer = Docs.find({}).observe({
added: (doc) => {
this.added('collectionName', doc._id, transform(doc));
},
changed: (doc) => {
this.changed('collectionName', doc._id, transform(doc));
},
removed: (doc) => {
this.removed('collectionName', doc._id);
}
});
this.onStop(() => observer.stop());
this.ready();
});
无论哪种方式都有效。
相关文章:
- 使用 JQuery 修改函数写入文档的数据
- 用于修改文档元素的 PHP 代码
- 复制和修改元素,以便在html文档的另一部分使用它们
- firefox扩展可以修改HTML文档的DOM,然后保存为HTML
- 什么时候是“;“安全”;以在解析文档时修改给定的html元素/节点
- 修改文档后如何重定向到应用程序的新页面
- 当按下后退按钮时,Firefox 会记住文档修改
- 通过 Google 文档中的脚本修改表格
- 更少:文档加载后加载的文件上的“修改变量”
- 在将html添加到文档中之前,如何修改ajax调用中的html
- 动态修改DOM并添加到文档中
- 如何修改文档中DIV元素的子集
- 在使用 Chrome 扩展程序加载之前,使用 document_start 修改文档 html
- 在发布文档之前,如何在find()中修改对象级别的文档
- 修改变量而非文档中HTML的HTML标记
- Javascript从上次修改文档到现在的时间
- jQuery文档修改功能
- 如何修改这段代码,使文档每次都搜索它
- 修改“string"TXT文档中的值
- 猫鼬:找到子文档并修改它的数组