使用mongoose

时间:2016-01-24 09:24:36

标签: node.js mongodb

我试图使用mongoose将嵌套对象保存到我的mongo数据库。

我希望能够使用channel.keyboard.link访问数据,频道是频道名称,但我无法弄清楚如何实现这一目标。< / p>

如何在通道名称下嵌套数据,以便我可以访问以下数据: summit1g.k​​eyboard.link

例如:

summit1g: {keyboard: "RGB K70, link: "http://linktokeyboard.com"}

对于noob问题感到抱歉,提前感谢您的帮助!

这是我的架构:

var streamSchema = new Schema({
channel: String,
keyboard: {name: String, link: String, count: Number},
mouse: {name: String, link: String, count: Number},
monitor: {name: String, link: String, count: Number},
headset: {name: String, link: String, count: Number},
card: {name: String, link: String, count: Number}
});

将数据保存到数据库:

var newStream = Stream({
channel: "summit1g",
keyboard: {name: "RGB K70", link: "http://amzn.to/1dYz0fZ", count: 0},
mouse: {name: "Final Mouse", link: "http://amzn.to/1HXYOSv", count: 0},
headset: {name: "Audio Technica", link: "http://amzn.to/1LfVc1p", count: 0},
monitor: {name: "ASUS", link: "http://amzn.to/1yZGNhK", count: 0},
card: {name: "Aver Media", link: "http://amzn.to/1AxA92G", count: 0}
});

1 个答案:

答案 0 :(得分:1)

keyboard等数据字段的属性为count。所以可能有一个以上的对象。你需要数组。

const streamSchema = new Schema({
  channel: String,
  keyboard: [{name: String, link: String, count: Number}],
  mouse: [{name: String, link: String, count: Number}],
  monitor: [{name: String, link: String, count: Number}],
  headset: [{name: String, link: String, count: Number}],
  card: [{name: String, link: String, count: Number}]
});

我认为即使字段计数没有必要,数组元素的索引也是计数。

但是在您的方案中,您可以使用此类查询:

query.find({ 'channel': 'summit1g', 'keyboard.name': 'RGB K70', 'keyboard.link': 'http://linktokeyboard.com'})