【问题标题】:Cannot post ref id to parrent collection mongoDB无法将 ref id 发布到父集合 mongoDB
【发布时间】:2020-06-10 19:28:54
【问题描述】:

我试图在 mongoDB 中插入两条记录。一个作为新集合,另一个作为 ref id。

架构示例 公司{ 名称:Acme 公司, 地点:[refID] }

id 和位置负载将在请求正文中发送。

addNewLocation: (req, res) => {
        
        let {id, ...payload} = req.body;
        
        db.Location.create(payload)
            .then( record => {
                let refId = record._id
                db.Company.findOneAndUpdate( {_id: id} , { $push: { locations: refId } }, { new: true })
            })
            .then( result => {
                res.status(201).json({success: true},{result})
            })
            .catch( err => {
                res.status(422).json({success: false},{err})
            })
    }

查看更新时(在 Robo3T 上),它似乎正在将文档插入该位置,但并未在公司集合中插入参考 ID。有什么想法可能导致这种情况吗?

【问题讨论】:

    标签: javascript mongodb express mongoose-schema


    【解决方案1】:

    当你想推 ref 时,你可能会弄错位置拼写大小写 它可能是 Locations 作为您的架构文件名称或将您的架构字段更改为 locations。 您可以在您的公司架构中尝试这样做

     {
        name: String,
        locations:[
          {
          type: Schema.Types.ObjectId,
          ref: "Location"
         }
        ]
     }
    

    【讨论】:

    • 在模型中它是“位置”
    • 使用 db.Company.findOneAndUpdate( {_id: id} , { $push: { Location: refId } }, { new: true }) })
    【解决方案2】:
    createNewLocation: (req, res) => {
        let { companyId , ...payload } = req.body;
    
        db.Location.create(payload)
        .then(({_id}) => {
           return db.Company.findOneAndUpdate(companyId, {$push:{location: _id}},{new: true})
        })
        .then(()=>{
            res.status(201).json({success: true})
        })
        .catch((err)=>{
            res.status(422).json({success: false})
        })
    }
    

    这是解决方案,只需要返回。

    【讨论】:

      猜你喜欢
      • 2015-02-02
      • 2017-08-23
      • 2016-09-12
      • 1970-01-01
      • 2015-08-08
      • 1970-01-01
      • 2016-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多