【问题标题】:Push ObjectId in Mongoose在 Mongoose 中推送 ObjectId
【发布时间】:2018-07-02 10:35:05
【问题描述】:

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

问题:

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

【问题讨论】:

    标签: javascript node.js express mongoose passport.js


    【解决方案1】:

    在您返回时,您还调用了 .save(),因此当您删除时重复和单个输入

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

    将您的回报放在 .then 或 .catch 中以从 mongo 检索响应

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

    【讨论】:

      猜你喜欢
      • 2022-01-13
      • 1970-01-01
      • 2021-03-03
      • 2012-08-20
      • 2018-02-13
      • 2018-09-14
      • 1970-01-01
      • 2018-05-20
      • 2015-05-02
      相关资源
      最近更新 更多