Mern 将对象推送到MongoDB中的数组
抱歉,我打了一个相当常见的问题,但我的最终结果有点奇怪 我尝试运行的代码应该基于几个条件将对象推入现有对象的数组中,但尽管它成功地添加了一个新对象,但存在的唯一属性是自动生成的ObjectID 我的模式和路线如下Mern 将对象推送到MongoDB中的数组,mern,Mern,抱歉,我打了一个相当常见的问题,但我的最终结果有点奇怪 我尝试运行的代码应该基于几个条件将对象推入现有对象的数组中,但尽管它成功地添加了一个新对象,但存在的唯一属性是自动生成的ObjectID 我的模式和路线如下 const paymentSchema = new Schema({ year: { type: String, default: new Date().getFullYear() }, month: { type: String, default: new Date().toLoca
const paymentSchema = new Schema({
year: { type: String, default: new Date().getFullYear() },
month: { type: String, default: new Date().toLocaleDateString('default', {month: 'long'}) },
payments : [{
memberID : { type: String, required: true},
package: { type: String, required: true }
}]
},{
路线
router.route('/update/:id').post((req, res) => {
const payments = {
memberID: req.body.payments.memberID,
package: req.body.payments.package
}
const newPayment = new Payments({
payments
});
Payments.findOneAndUpdate({_id: req.params.id}, {$push: {payments: newPayment}})
.then(() => res.json('Payment added to existing period...'))
.catch(err => res.status(400).json('Error: ' + err));
}))
以及表格提交的逻辑
const onSubmitData = data => {
const currentYear = new Date().getFullYear();
const currentMonth = new Date().toLocaleDateString('default', {month: 'long'});
const lastEntry = allPayments[allPayments.length - 1]
const payment = {
payments: {
memberID: data.member.value._id,
package: data.paidPackage.value._id
}
}
if(allPayments.length === 0){
axios.post('http://localhost:5000/payments/add', payment)
.then(res => console.log(res.data))
}else if(lastEntry.year == currentYear && lastEntry.month == currentMonth) {
axios.post(`http://localhost:5000/payments/update/${lastEntry._id}`, payment)
.then(res => console.log(res.data))
} else {
axios.post('http://localhost:5000/payments/add', payment)
.then(res => console.log(res.data))
}
}
通过第二个条件的帖子显示为第一个条目看起来很好,后续条目没有细节
更新
我将{$push:{payments:newPayment}}
更改为{$push:req.body}
,它似乎按预期工作。但是,如果我连续输入条目,而不在每个条目上重新加载页面,那么我将得到上一期的mongodb条目。为什么会这样
我假设这和内部状态有关,或者