【发布时间】:2021-03-04 11:07:05
【问题描述】:
我使用这种地址架构并在多个架构中使用它。 一切正常,只有当我更新地址时
const addressSchema = new mongoose.Schema({
street: String,
number: String,
postcode: String,
city: String,
comment: String,
country: {
type: 'ObjectId',
ref: 'Country'
},
location: {
type: pointSchema,
default: () => ({}),
index: '2dsphere',
}
});
addressSchema.pre('save', async function (next) {
console.log('subdocument address pre.save'); // is triggred
//create geolocation
});
addressSchema.pre('updateOne', async function (next) {
console.log('subdocument address pre.updateOne'); // not triggred, no error
//update geolocation
});
Mongoose 的文档仅涉及中间件保存和验证。
https://mongoosejs.com/docs/subdocs.html#what-is-a-subdocument-
但是做我想做的最好的解决方案是什么?
其他信息
const pointSchema = new mongoose.Schema({
type: {
type: String,
enum: ['Point'],
default: 'Point'
},
coordinates: {
type: [Number],
default: null,
}
});
const common = require('./common');
const customerSchema = new Schema({
//...
address: {
type: common.addressSchema,
default: () => ({}),
},
})
const providerSchema = new Schema({
//...
address: {
type: common.addressSchema,
default: () => ({}),
},
})
"address": {
"_id": "6043a5f3a8cad615cd8eab3a",
"location": {
"type": "Point",
"coordinates": [
48.818511962890625,
2.31961989402771
],
"_id": "603fed0629390b30d53bed3e"
},
"street": "Avenue des Tulipes",
"postcode": "78500",
"number": "69",
"city": "Montrouge",
"comment": null,
"country": "5f626eb337fd4d75ab694112"
},
当我们创建新客户时,addressSchema 的中间件“save”没有问题,但是当我们更新客户时,所有数据都正确更新,但不会触发 addressSchema 的中间件“updateOne”。
【问题讨论】:
-
您能否发布未在中间件中触发的 pointSchema 和更新查询。
-
此地址架构是客户架构的子架构吗?如果是,请在您的问题中说明。如果您也发布更新查询也会有所帮助。
-
它是多个模式的子模式,它用于每个具有地址的模式
标签: mongoose updates middleware