我正在尝试将一个深层嵌套的文档保存在另一个文档中,但是经过几次尝试后我还是无法做到这一点

时间:2019-06-08 12:11:17

标签: node.js express mongoose

假设我有这两种模型

// INSTALLATION MODEL
const InstallationSchema = new Schema({
  installrefno: { type: String },
 //I want to access and save only the serialno which is nested inside the products
  serialno: {
  type: mongoose.Schema.Types.ObjectId,
  ref: "Proreg"
  }
});
module.exports = InstallationDetails = mongoose.model(
  "Installation",
  InstallationSchema
);

// PROREG MODEL
const ProregSchema = new Schema({
  refno1: { type: String },
   products: [
    {
      oem: {
        type: Schema.Types.ObjectId,
        ref: "company"
      },
      category: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "productcategory"
      },
      subcategory: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "productsubcategory"
      },
      modelno: {
        type: String
      },
      serialno: {
        type: String,
        required: true
      }
      }
    }
  ],
});

module.exports = Proreg = mongoose.model(
  "Proreg",
  ProregSchema
);

当我使用此代码创建新安装时,它将使用Proreg的ID,很明显, 但它也带走了随之而来的所有产品。

//INSTALLATION CREATE ROUTE
router.post("/new",(req, res) => {
  const newInstall = new Install({
    installrefno: req.body.installrefno,
    serialno: req.body.proregid   //serialno: "A345"
  });

  newInstallationDetails
    .save()
    .then(installation => res.json(installation))
    .catch(err => res.json(err));
});

//RESULT
[
    {
        "_id": "5cfc53748fcc7b048043f555",
        "installrefno": "rererererererere",
        "serialno": {
            "_id": "5cf10fcc4cb6352abcfe094a",
            "refno1": "test2",
            "products": [
                {
                    "_id": "5cf10fea4cb6352abcfe094b",
                    "oem": "5cb6e026042460131454cf45",
                    "category": "5c960902e5cf3429e06beb6c",
                    "subcategory": "5ca35fbed6e1430df88954a6",
                    "modelno": "A123888",
                    "serialno": "A345"
                },
                {
                    "_id": "5cf10ffb4cb6352abcfe094c",
                    "oem": "5c986a1e9b6bc614b8a551b9",
                    "category": "5c960902e5cf3429e06beb6c",
                    "subcategory": "5ca35fbed6e1430df88954a6",
                    "modelno": "QW123",
                    "serialno": "B345"
                }
            ],
            "__v": 2
        },
        "__v": 0
    }
]

我希望只能选择一个只说“ A345”的产品,我该怎么做。有人可以帮我吗?

0 个答案:

没有答案