最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to store object in mongoose schema? - Stack Overflow

programmeradmin1浏览0评论

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
Add a comment  | 

5 Answers 5

Reset to default 5

You 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

发布评论

评论列表(0)

  1. 暂无评论