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?
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?
Share Improve this question asked Jun 24, 2017 at 17:45 fogenfogen 911 gold badge1 silver badge3 bronze badges 1- what you are describing is an array of objects not an object – lukas_o Commented Jan 13, 2020 at 12:24
5 Answers
Reset to default 5You must create another mongoose schema:
var address = Schema({ street: String, city: String});
And the type of addresses will be Array< address >
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,
});
//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
You are actually storing an array.
var personSchema = Schema({
_id : Number,
name : String,
surname : String,
addresses : []
});
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