[英]Push ObjectId in Mongoose
I'm using express, passport, and mongoose. 我正在使用快递,护照和猫鼬。 I don't know why but the code below pushes same newTaxReturn._id
twice into user.taxReturnIds
field. 我不知道为什么,但是下面的代码两次将相同的newTaxReturn._id
推入user.taxReturnIds
字段。 If I remove user.save().catch(() => {})
line, it pushes the newTaxReturn._id
correctly ie just once. 如果我删除user.save().catch(() => {})
行,它将正确推送newTaxReturn._id
,即仅推送一次。 The user argument is from passport. 用户参数来自护照。
Problem: 问题:
const createTaxReturn = ({ user }) => {
const newTaxReturn = new TaxReturn({ userId: user._id })
user.taxReturnIds.push(newTaxReturn._id)
user.save().catch(() => {})
return newTaxReturn.save().catch(() => {})
}
Schema: 架构:
const User = new mongoose.Schema({
taxReturnIds: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'TaxReturn',
}],
})
const TaxReturn = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
})
On your return you are also calling .save() thus the duplication and the single input when you remove 在返回时,您还调用.save(),因此删除时将复制和输入单个
user.save().catch(() => {})
place your return in a .then or .catch to retrieve the response from mongo 将您的退货放在.then或.catch中以从mongo检索响应
user.save().catch(error => { if (error) return error })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.