选项一
我建议您为您的标签
创建一个模型
attributes: {
ideas: {
collection: 'idea'
},
name: {
type: 'string'
}
}
接下来,编辑您的 Idea 模型以引用您的 Tag 模型
attributes: {
tags: {
collection: 'tag'
},
name: {
type: 'string'
}
}
然后要获得与“tagX”相关的所有想法:
var tag = "tagX";
// This same code should also work with an array,
// but then you will have to use find instead of findOne
// var tag = ["tagX", "tagY", "tagZ"]
Tag.findOne({name: tag}).populate('ideas').then(function (tag) {
// Do anything you want with the Ideas.
tag.ideas.forEach(function(idea) {
console.log(idea);
});
}).catch(console.err);
使用标签“tagX”和“tagY”创建创意“Some Grand Idea”
在集合中添加和删除标签非常容易。
Promise.all([Idea.create({ name: 'Some Grand Idea'}),
Tag.create({ name: 'TagX'}),
Tag.create({ name: 'TagY'})]).
spread(function (idea, tagX, tagY) {
// Add tagX
idea.tags.add(tagX.id);
// Add tagY
idea.tags.add(tagY.id);
// To remove a tag, simply call remove
// idea.tags.remove(1)
idea.save(console.log);
}).catch(console.log);
因此,总而言之,获得一个 Idea 模型。并向 Idea.tags 集合添加/删除标签模型。
这适用于两种方式,即您可以获得一个 Tag 模型并将一个想法添加到 Tag.ideas 集合tag.ideas.add(someIdea.id) 并且它的工作原理相同。
选项二
或者,以您设置的方式使用创意模型。
用一些标签获取想法:
Idea.find({ tags: { 'like': '%tagX%' }})
通过标签列表获取想法:
Idea.find({
or : [
{ tags: { 'like': '%\'tagX\'%' } },
{ tags: { 'like': '%\'tagY\'%' } },
{ tags: { 'like': '%\'tagZ\'%' } }
]
})