Reputation: 91
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?
Upvotes: 8
Views: 21621
Reputation: 190
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
Upvotes: 0
Reputation: 4951
You are actually storing an array.
var personSchema = Schema({
_id : Number,
name : String,
surname : String,
addresses : []
});
Upvotes: 1
Reputation: 6482
//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
Upvotes: 2
Reputation: 1067
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,
});
Upvotes: 2
Reputation: 562
You must create another mongoose schema:
var address = Schema({ street: String, city: String});
And the type of addresses will be Array< address >
Upvotes: 5