我有2组代码。第一套我不认为为什么不起作用,但是第二套却不能。我必须创建对象的副本,添加希望添加的属性,保存到MongoDB中,然后最后删除旧对象。我有某种更好的方法被我忽略了吗?
订购模式:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const orderSchema = new Schema({
order_no: {
type: String,
minlength: 8,
unique: true,
required: true,
validate(value) {
if (value < 0) {
throw new Error('less than zero.')
}
}
},
customer_no: {
type: String,
minlength: 8,
unique: true,
required: true,
validate(value) {
if (value < 0) {
throw new Error('less than zero.')
}
}
},
invoice_no: {
type: String,
minlength: 8,
unique: true,
required: true,
validate(value) {
if (value < 0) {
throw new Error('less than zero.')
}
}
},
lines: {
type: Array,
required: true
},
status: {
type: String,
required: true,
default: 'Released'
}
}, {
timestamps: true
});
const Order = mongoose.model('Order', orderSchema);
module.exports = Order;
第一组:
try {
const customer_no = request.params.id;
const order = await Order.findOne({ customer_no });
if (!order) {
return response.status(404).send();
}
for (let i = 0; i < order.lines.length; i ++) {
order.lines[i].updated_qty = order.lines[i].expected_qty;
}
await order.save();
response.status(201);
response.send(order);
} catch (error) {
response.status(500);
response.send(error.message);
}
第二组:
try {
const customer_no = request.params.id;
const current = await Order.findOne({ customer_no });
if (!current) {
return response.status(404).send();
}
const order = new Order({
order_no: current.order_no,
customer_no: current.customer_no,
invoice_no: current.invoice_no,
lines: current.lines
});
for (let i = 0; i < current.lines.length; i ++) {
order.lines[i].updated_qty = current.lines[i].expected_qty;
}
await order.save();
await current.delete();
response.status(201);
response.send(order);
} catch (error) {
response.status(500);
response.send(error.message);
}
我没有任何错误,第二组代码也可以使用,但是我希望第一组代码可以使用,因此我可以保留创建文档时的时间戳以及更新文档时的当前时间戳。