Jayson H
Jayson H

Reputation: 2048

Saving nested objects using mongoose

I'm trying to save a nested object to my mongo database using mongoose.

I would like to be able to access the data using channel.keyboard.link with channel being the name of the channel, but I can't figure out how to accomplish this.

How can I nest the data under a channel name so that I can access the data like: summit1g.keyboard.link

Ex:

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

Sorry for the noob question, thanks in advance for the help!

Here is my schema:

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}
});

Saving the data to the database:

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}
});

Upvotes: 0

Views: 567

Answers (1)

Arthur Osipenko
Arthur Osipenko

Reputation: 123

Your data field like keyboard have property count. So there maybe more then one object. You need array.

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}]
});

I think even field count not necessary, index of array element will be count number.

But in your scheme you can use such query:

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

Upvotes: 2

Related Questions