8

In node.js I have three variables:

var name = 'Peter';
var surname = 'Bloom';
var addresses = [
    {street: 'W Division', city: 'Chicago'},
    {street: 'Beekman', city: 'New York'},
    {street: 'Florence', city: 'Los Angeles'},
];

And schema:

var mongoose = require('mongoose')
  , Schema = mongoose.Schema;

var personSchema = Schema({
  _id     : Number,
  name    : String,
  surname : String,
  addresses : ????
});

What type and how do I use it in schema? How is the best way for this?

fogen
  • 91
  • 1
  • 1
  • 3

5 Answers5

5

You must create another mongoose schema:

var address = Schema({ street: String, city: String});

And the type of addresses will be Array< address >

Kenany
  • 446
  • 3
  • 11
2

The Solution to save array is much simple,Please check below code

Adv.save({addresses: JSON.stringify(addresses)})

Your schema will look like it

var personSchema = Schema({
 _id     : Number,
 name    : String,
 surname : String,
 addresses : String,
});
Naveen Kumar
  • 987
  • 11
  • 11
  • 2
    only one problem with this way of storing Schema, Say we wanted to be able to query the address data on here? like for example, get the list of results that hit for the Los Angeles, then we wouldnt be able to query those records – Richard Abear Jan 27 '19 at 10:06
2
//Your Schema is very easy like below and no need to define _id( MongoDB will automatically create _id in hexadecimal string)
var personSchema = Schema({
  name    : String,
  surname : String,
  addresses : [{
    street: String,
    city: String
  }]

var addresses= [
    {street: 'W Division', city: 'Chicago'},
    {street: 'Beekman', city: 'New York'},
    {street: 'Florence', city: 'Los Angeles'}
];
//Saving in Schema
var personData = new personSchema ({
  name:'peter',
  surname:'bloom',
  addresses:addresses  
})
personData.save();

Hope this may solve your issue

Ratan Uday Kumar
  • 5,738
  • 6
  • 35
  • 54
1

You are actually storing an array.

var personSchema = Schema({
  _id     : Number,
  name    : String,
  surname : String,
  addresses : []
});
Isaac Pak
  • 4,467
  • 3
  • 42
  • 48
0

you can use ref in personSchema

var personSchema = Schema({
  _id     : Number,\n
  name    : String,
  surname : String,
  addresses : [{ref:Adress}]
});

var address = Schema({street: String, city: String});


mongoose.model('PersonSchema', personSchema);
mongoose.model('Adress', adress);

'ref' is used to making a reference of address and used in personSchema

krnitheesh16
  • 152
  • 1
  • 6