如何检索给定 post 中引用的所有标签文档?
How to retrieve all Tag documents referred in the given post?
我有以下 Post 和标签模型。 Posts 具有包含 tagId 的标签数组字段。
var telescopeId1 = Posts.insert({
title: 'What is/are the main type',
userId: sacha._id,
author: sacha.profile.name,
details: 'Can someone recommend...',
submitted: new Date(now - 9 * 3600 * 1000),
commentsCount: 1,
tags: [{tagId: valveTagId},{tagId: pumpTagId}]
});
var valveTagId = Tags.insert({
slug: 'valve-tags',
name: 'valve tags',
submitted: new Date(now - 7 * 3600 * 1000),
description: 'Valve tags help relay.'
});
var pumpTagId = Tags.insert({
slug: 'pump',
name: 'pump',
submitted: new Date(now - 7 * 3600 * 1000),
description: 'PUMP is..,'
});
在 Meteor 中,我正在尝试使用以下函数检索给定 post 中引用的所有标签文档:
tags: function() {
return Tags.find({_id: this.tags.tagId});
}
但是我在 return 中得到空标签数组对象,为什么?
this.tags
将是一个数组。所以它没有 tagId
属性.
这是查找所有标签的方式:
var tagIds = _.pluck(this.tags, 'tagId');
return Tags.find({_id: {$in: tagIds}});
我要做一些假设:
- 上面的代码按照为
valveTagId
和 pumpTagId
提供定义值的顺序执行。
- 您的
tags
助手中的上下文 (this
) 是一个 post 文档。
问题
助手正在尝试执行以下操作:
Tags.find({_id: [{tagId: valveTagId}, {tagId: pumpTagId}].tagId});
这没有任何意义,因为数组没有 tagId
属性.
解决方案
正确的实现会提取该列表中所有带有 _id
的 ID 和 find
标签。这应该有效:
tags: function() {
var tagIds = _.pluck(this.tags, 'tagId');
return Tags.find({_id: {$in: tagIds}});
}
改进的解决方案
标签 ID 以一种笨拙的方式存储以执行此连接。而不是存储:
tags: [{tagId: valveTagId}, {tagId: pumpTagId}]
考虑像这样存储一个 ID 数组:
tags: [valveTagId, pumpTagId]
现在helper可以写成:
tags: function() {
return Tags.find({_id: {$in: this.tags}});
}
我有以下 Post 和标签模型。 Posts 具有包含 tagId 的标签数组字段。
var telescopeId1 = Posts.insert({
title: 'What is/are the main type',
userId: sacha._id,
author: sacha.profile.name,
details: 'Can someone recommend...',
submitted: new Date(now - 9 * 3600 * 1000),
commentsCount: 1,
tags: [{tagId: valveTagId},{tagId: pumpTagId}]
});
var valveTagId = Tags.insert({
slug: 'valve-tags',
name: 'valve tags',
submitted: new Date(now - 7 * 3600 * 1000),
description: 'Valve tags help relay.'
});
var pumpTagId = Tags.insert({
slug: 'pump',
name: 'pump',
submitted: new Date(now - 7 * 3600 * 1000),
description: 'PUMP is..,'
});
在 Meteor 中,我正在尝试使用以下函数检索给定 post 中引用的所有标签文档:
tags: function() {
return Tags.find({_id: this.tags.tagId});
}
但是我在 return 中得到空标签数组对象,为什么?
this.tags
将是一个数组。所以它没有 tagId
属性.
这是查找所有标签的方式:
var tagIds = _.pluck(this.tags, 'tagId');
return Tags.find({_id: {$in: tagIds}});
我要做一些假设:
- 上面的代码按照为
valveTagId
和pumpTagId
提供定义值的顺序执行。 - 您的
tags
助手中的上下文 (this
) 是一个 post 文档。
问题
助手正在尝试执行以下操作:
Tags.find({_id: [{tagId: valveTagId}, {tagId: pumpTagId}].tagId});
这没有任何意义,因为数组没有 tagId
属性.
解决方案
正确的实现会提取该列表中所有带有 _id
的 ID 和 find
标签。这应该有效:
tags: function() {
var tagIds = _.pluck(this.tags, 'tagId');
return Tags.find({_id: {$in: tagIds}});
}
改进的解决方案
标签 ID 以一种笨拙的方式存储以执行此连接。而不是存储:
tags: [{tagId: valveTagId}, {tagId: pumpTagId}]
考虑像这样存储一个 ID 数组:
tags: [valveTagId, pumpTagId]
现在helper可以写成:
tags: function() {
return Tags.find({_id: {$in: this.tags}});
}