简体   繁体   English

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

[英]Cannot post ref id to parrent collection mongoDB

Im trying to insert two records into mongoDB.我试图在 mongoDB 中插入两条记录。 One as a new collection the other a ref id.一个作为新集合,另一个作为参考 ID。

Sample of schema Company{ name: Acme Company, Locations: [refID] }模式公司示例{名称:Acme Company,位置:[refID]}

the id & location payload will be sent in the body of the request. 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}) }) }

when viewing the update (on Robo3T) it appears to be inserting a document into the location, but it doesn't insert the ref id in the companies collection.查看更新时(在 Robo3T 上),它似乎正在将文档插入该位置,但它没有在公司集合中插入参考 ID。 Any ideas what might be causing this?有什么想法可能导致这种情况吗?

Probably you mistake locations spelling case when you want to push ref It may be Locations as you schema filed name or change your schema field to locations .当您想要推送 ref 时,您可能会错误的位置拼写大小写它可能是Locations作为您的架构文件名称或将您的架构字段更改为locations You can try by this in your company schema您可以在您的公司架构中尝试这样做

 {
    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})
    })
}

Here is the solution, just needed a return.这是解决方案,只需要退货。

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

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