MongoDb : How to insert additional object into object collection?

前端 未结 2 616
执念已碎
执念已碎 2021-02-13 14:00

I have a document \"owner\" that can have \"n\" number of camps and camps have \"instructors\" and instructors have \"classes\". Earlier I tried accomplishing this with nested a

相关标签:
2条回答
  • 2021-02-13 14:37
    var newObject = {usuario: req.body.usuario, fecha: req.body.fecha, edit: 
    req.body.edit};
    
    await Documentos.findByIdAndUpdate(id,
     { deleted_doc: true,
     $push: { history: newObject } }); 
    res.json({ status: 'Documentos Updated' });
    
    0 讨论(0)
  • 2021-02-13 14:44

    As other mentioned, The structure you want is not valid. I recommend the following structure for your owner document:

        {
        "_id" : ObjectId("51c9cf2b206dfb73d666ae07"),
        "firstName" : "john",
        "lastName" : "smith",
        "ownerEmail" : "john.smith@gmail.com",
        "camps" : [
                {
                        "name" : "cubs-killeen",
                        "location" : "killeen"
                },
                {
                        "name" : "cubs-temple",
                        "location" : "temple"
                }
        ],
        "instructors" : [
                {
                        "firstName" : "joe",
                        "lastName" : "black"
                },
                {
                        "firstName" : "will",
                        "lastName" : "smith"
                }
        ]
    }
    

    and then

    db.stack.update(
      { ownerEmail: "john.smith@gmail.com" },
      {
        $push: {
          camps: { name: "cubs-killeen", location: "some other Place" }
        }
      }
    );
    

    Having this, you can add camps like this:

    Hope it helps.

    0 讨论(0)
提交回复
热议问题