gpt4 book ai didi

javascript - 在 Mongoose 中推送 ObjectId

转载 作者:行者123 更新时间:2023-12-03 02:39:08 25 4
gpt4 key购买 nike

我使用的是 Express、Passport 和 Mongoose。我不知道为什么,但下面的代码将相同的 newTaxReturn._id 两次推送到 user.taxReturnIds 字段中。如果我删除 user.save().catch(() => {}) 行,它会正确推送 newTaxReturn._id ,即仅推送一次。用户参数来自 Passport 。

问题:

const createTaxReturn = ({ user }) => {
const newTaxReturn = new TaxReturn({ userId: user._id })
user.taxReturnIds.push(newTaxReturn._id)
user.save().catch(() => {})
return newTaxReturn.save().catch(() => {})
}

架构:

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',
},
})

最佳答案

返回时,您还会调用 .save() ,因此删除时会出现重复和单个输入

user.save().catch(() => {})

将返回值放入 .then 或 .catch 中以检索来自 mongo 的响应

user.save().catch(error => { if (error) return error })

关于javascript - 在 Mongoose 中推送 ObjectId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48404568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com