我有一个方法的架构 - 2个变种。它们在第一次添加地址时都能正常工作,但是当添加另一个地址时(即当它经过for循环时),第一版会爆炸。我吹嘘的意思是它似乎破坏了我的订单实例 - 没有更多的'保存'方法。
架构
var Address = new Schema({
type: { type: String, enum: ['shipping', 'billing'] },
street: { type: String, required: true },
city: { type: String, required: true },
region: String,
country: String,
postal: { type: String, required: true },
});
var Order = new Schema({
email: {
type: String
},
address: [Address]
});
现在,如果我在我的架构中添加了addAddress()方法。以下是我尝试的两个版本。
// Version 1 - has issues on subsequent call
Order.methods.addAddress = function() {
var data = { type: 'shipping', city: 'Tempe', postal: '85281', street: '420 Mill Ave'};
for(var i = this.address.length-1; i >=0; i--) {
if(this.address[i].type === type) {
delete address[i];
}
}
this.address.push(data);
}
// Version 2 - works fine
Order.methods.addAddress = function() {
var data = { type: 'shipping', city: 'Tempe', postal: '85281', street: '420 Mill Ave'};
var found = false;
for(var i = this.address.length-1; i >=0; i--) {
if(this.address[i].type === type) {
found = true;
this.address[i] = data;
}
}
if(!found)
this.address.push(data);
}
使用V1后尝试保存会产生此错误:
Uncaught Exception
TypeError: Object #<Object> has no method 'save'
at /var/node_modules/mongoose/lib/document.js:1270:13
at Array.forEach (native)
at model.pre.err.stack (/var/node_modules/mongoose/lib/document.js:1252:12)
at model._next (/var/node_modules/mongoose/node_modules/hooks/hooks.js:50:30)
at model.proto.(anonymous function) [as save] (/var/node_modules/mongoose/node_modules/hooks/hooks.js:96:20)
at Promise.<anonymous> (/var/controllers/cart.js:79:11)
at Promise.<anonymous> (/var/node_modules/mongoose/node_modules/mpromise/lib/promise.js:171:8)
at Promise.EventEmitter.emit (events.js:95:17)
at Promise.emit (/var/node_modules/mongoose/node_modules/mpromise/lib/promise.js:88:38)
at Promise.fulfill (/var/node_modules/mongoose/node_modules/mpromise/lib/promise.js:101:20)
我们来看下面的代码:
Order.findById(id.exec(function(err, o) {
o.addAddress('shipping', { street: '1000 Mill Ave', city: 'Tempe', postal: '85281' });
console.log(o);
o.save(function(err, order) {
});
})
注意控制台通话?在每个变体上,看起来订单对象都是正确的:
{
_id: 007d0000b10000000000000c,
address: [{
street: '420 Mill Ave',
postal: '85281',
city: 'Tempe',
type: 'shipping'
_id: 52b2459f1547a5e12300000b
}]
}
但似乎已经失去了诸如“保存”方法之类的东西。
有什么想法吗?
答案 0 :(得分:0)
您将地址定义为dict而不是地址对象。相反,你应该做这样的事情:
Order.methods.addAddress = function(type, data, next) {
// Have your removal code here
var self = this
var address = new Address(data)
address.save(function(err, address) {
if (err) {
...
} else {
self.address.push(address)
next()
}
})
}
请注意,我正在根据模式定义使用地址对象填充地址数组。