node.js - 如何将架构添加到另一个架构数组?
问题描述
我有地址架构和客户架构。我的客户架构中有一个字段地址数组。我将发送一个地址模型作为我的请求正文和客户 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 文档对我来说还不够。这个链接似乎是我需要的,但我不知道如何解决这个问题。
解决方案
好的,所以基本上你要寻找的是:关联。您需要在 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);
});
检查文档以获取更多信息。
推荐阅读
- excel - 保存文件时忽略斜线
- php - Vagrant 虚拟主机/共享文件夹无法访问
- java - 将 Jackson 注释添加到招摇生成的类中
- jquery - 使用 jquery 循环遍历表值以进行数据库更新
- security - Thorntail 基本认证
- view - WheelPicker OnwheelChangeListener 返回 null onpause
- c# - ASP.NET MVC 操作方法定期不接收 GET 参数
- javascript - 在 Twitter、Linkedin、Pinterest 和 Instagram 上分享计数
- android - 使 Glide 作为所有类的单例工作
- excel - 无法获取 WorkItem 中的自定义字段值