繁体   English   中英

无法将 ref id 发布到父集合 mongoDB

[英]Cannot post ref id to parrent collection mongoDB

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

模式公司示例{名称:Acme Company,位置:[refID]}

id & location 有效负载将在请求正文中发送。

 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。 有什么想法可能导致这种情况吗?

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

 {
    name: String,
    locations:[
      {
      type: Schema.Types.ObjectId,
      ref: "Location"
     }
    ]
 }
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})
    })
}

这是解决方案,只需要退货。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM