如何在mongoose模式中存储对象?

时间:2017-06-24 17:45:19

标签: javascript node.js mongodb mongoose

在node.js中我有三个变量:

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

架构:

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

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

什么类型以及如何在架构中使用它?最好的方法是什么?

4 个答案:

答案 0 :(得分:1)

保存数组的解决方案非常简单,请查看下面的代码

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

您的架构看起来像

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

答案 1 :(得分:0)

您必须创建另一个mongoose架构:

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

地址类型为数组<地址>

答案 2 :(得分:0)

您可以在personSchema中使用ref

x, y, z
-10,4,30
-4,3,20
10,10,12
-11.5,3,-33.2
-5,0,23
-4,-2,8
0,2,1
5,12,42
11.2,5,23

'ref'用于引用地址,并用于personSchema

答案 3 :(得分:-1)

//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();

希望这可以解决您的问题