首页 > 解决方案 > 如何将架构添加到另一个架构数组?

问题描述

我有地址架构和客户架构。我的客户架构中有一个字段地址数组。我将发送一个地址模型作为我的请求正文和客户 ID 作为请求参数。如何将该地址保存到在客户模式中声明的地址数组?

这是我的客户架构

const customerSchema = mongoose.Schema ({
  _id: mongoose.Schema.Types.ObjectId,
  name: String,
  phone_number: String,
  password: String,
  type:{type:String,enum:['admin','user']},
  adresses:['Adress'],
  orders:[{type: mongoose.Schema.Types.ObjectId, ref: 'Order'}]
});

这是我的地址架构

const addressSchema= mongoose.Schema({
    _id:mongoose.Types.ObjectId,
    postalCode:Number,
    city:String,
    district:String,
    neighborhood:String,
    streetNumber:String,
    no:Number,
    buildingName:String,
    apartmentNumber:Number,
    floor:Number,
    coordinates:{
        latitude:Number,
        longitude:Number
    },
    addressName:String,
    customerId: {type: mongoose.Schema.Types.ObjectId,ref:'Customer'}


}); 

我不知道我将如何做到这一点。我正在寻找客户,我将把我的地址推送到这样的客户。

这就是我获得特定客户的方式

Customer.find({_id:req.params.customerId},(err,data)=>{
    if(err) return next(err);
    else{
      //What I am going to do here?
    }
});

首先,我应该在 Customer Schema 内的地址数组中放入什么类型?

其次,找到我要添加地址的客户后,我该怎么办?Mongoose 5.4.11 文档对我来说还不够。这个链接似乎是我需要的,但我不知道如何解决这个问题。

https://mongoosejs.com/docs/subdocs.html

标签: node.jsmongoosemongoose-schema

解决方案


好的,所以基本上你要寻找的是:关联。您需要在 User 和 Customer 模型之间建立连接。

我们会说地址属于用户和用户引用地址对象,例如 id。

考虑一个例子:

const personSchema = Schema({
  _id: Schema.Types.ObjectId,
  name: String,
  age: Number,
  stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

const storySchema = Schema({
  author: { type: Schema.Types.ObjectId, ref: 'Person' },
  title: String,
  fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});

const Story = mongoose.model('Story', storySchema);
const Person = mongoose.model('Person', personSchema);

现在让我们尝试为特定创建的故事分配作者:

const author = new Person({
  _id: new mongoose.Types.ObjectId(),
  name: 'Ian Fleming',
  age: 50
});

author.save(function (err) {
  if (err) return handleError(err);

  const story1 = new Story({
    title: 'Casino Royale',
    author: author._id    // assign the _id from the person
  });

  story1.save(function (err) {
    if (err) return handleError(err);
    // thats it!
  });
});

当您定义 Story 和 Person 之间的关系时,很容易操纵它们之间的引用。

在您的情况下,您应该在模型中定义一个引用,然后您就可以操作这些字段:

Customer.findOne({_id:req.params.customerId}, function(error, customer) {
  if (error) {
    return handleError(error);
  }
  customer.address = newAddress; // set customer's address to the desired address
  // console.log(customer.address.city);
});

检查文档以获取更多信息。


推荐阅读