【发布时间】:2019-10-31 09:07:00
【问题描述】:
我有一个包含 Events 的 mongoDB 数据库。每个事件由多个字段定义,包括一个流派数组(它们是由 {genre 和 subGenre} 组成的子文档)。
例如:一个事件可以是 {genre: "music", subGenre: "jazz"} 和 {genre: "music", subGenre: "blues"}。请参阅 event.js - 模型。在这种情况下,数据库的 Event 文档中的“genres”数组中添加了 2 个“genre”子文档。
回到我的节点应用程序 - 请参阅 query.ts - 我正在尝试研究如何运行一个查询,让用户搜索与其类型偏好匹配的所有事件。
所以:
- 事件由一系列类型(在数据库中)定义,并且
- 用户的偏好由一系列类型定义(在
申请)。
我希望定义一个 mongoDB 查询,该查询返回所有事件,其中两个数组之间存在任何 1 个 {genre, subGenre} 组合的匹配项。
我在 mongoDB 文档中查看了 $in Query Selector 并怀疑它可能需要使用...但是以编程方式,我如何编写一个扩展以包含所有值的查询query.ts 中的变量“searchGenres”?
非常感谢您的想法。
event.js:使用 Mongoose 定义的“事件”的 mongoDB 模型 - sn-p:
let mongoose = require('mongoose');
let EventSchema = new mongoose.Schema({
genres: [
{
genre: String,
subGenre: String
}
]
)};
module.exports = mongoose.model('Event', EventSchema);
query.ts:
import mongoose = require('mongoose');
let Event = require ('../models/event');
class Genre {
genre: string;
subGenre: string;
constructor (gen: string, sub: string) {
this.genre = gen;
this.subGenre = sub;
}
}
async function runQuery()
{
let searchGenres : Array<Genre> = new Array<Genre>();
// populate searchGenres with some data here... e.g.
const searchGenre1 : Genre = new Genre ('music', 'jazz');
const searchGenre2 : Genre = new Genre ('music', 'rock');
searchGenres.push(searchGenre1);
searchGenres.push(searchGenre2);
// Query logic here:
// Return all events from the database, if the 'genres' array
// in the document matches any element in the searchGenres array
// defined above..
const events = await Event.find ({
'genres': {?help? }
});
}
```
【问题讨论】:
标签: javascript mongodb typescript mongoose