【问题标题】:How to add object to collection inside another collection in MongoDB using Node.js如何使用 Node.js 将对象添加到 MongoDB 中另一个集合内的集合
【发布时间】:2016-06-23 21:59:44
【问题描述】:

我知道如何使用 Node.js 在 MongoDB 中将对象添加到集合中,例如:

router.post('/addProduct', function (req, res) {
    Partner.findByIdAndUpdate({ _id: req.body.partnerId }, { $push: { "products": { name: req.body.dataProduct.name } } }, { safe: true }, function (err, response) {
        if (err) throw err;
        res.json(response);
    });
});

但是如果在产品中是另一个表呢?我怎样才能简单地在那里添加对象?

假设这是我的架构:

var partnerSchema = new mongoose.Schema({
    name: String,
    products: [
        {
            name: String,
            campaignList: [
                {
                    name: String,
                    type: String,
                    startDate: Date,
                    endDate: Date,
                    paymentMethod: String,
                    partnerPayout: Number,
                    ourPayout: Number
                }
            ]
        }]
});

每个partnerproduct 中的ID 是默认._id 例如。 partner._idproduct._id。这就是为什么不在上面的模式中。但是我将它们作为req.parameter 从前端发送到后端 - 通常是这样,但我想肯定地说:)

【问题讨论】:

    标签: javascript node.js mongodb


    【解决方案1】:

    您最好自己定义广告系列的架构和模型,并使用_id通过引用将其添加到合作伙伴

    var partnerSchema = new mongoose.Schema({
        name: String,
        products: [
            {
                name: String,
                campaignList: [
                    { type : mongoose.Schema.Types.ObjectId, ref : 'campaignModel' }
                ]
            }]
    });
    var campaignSchema = new mongoose.Schema({
      name: String,
      type: String,
      startDate: Date,
      endDate: Date,
      paymentMethod: String,
      partnerPayout: Number,
      ourPayout: Number
    });
    var campaignModel = mongoose.model('campaignModel', campaignSchema);
    var partnerModel = mongoose.model('partnerSchema', partnerSchema);
    

    一个好的做法是查找您尝试嵌套半复杂数据或具有两个或三个以上键的对象的时间,并将它们提取到自己的集合中。它不仅可以更轻松地搜索这些文档,还可以更轻松地将它们与其他对象结合使用。

    确保在查询期间调用 .populate(),以便 MongoDB 知道嵌套其他集合中的文档,否则,您将只有一个 ObjectId 数组。

    【讨论】:

      【解决方案2】:

      首先匹配所需的产品数组位置。您可以通过测试一个简单的发现来确认这一点:

      Partner.find({_id: req.body.partnerId), 'products.name': req.body.dataProduct.name }, { 'products.$': 1})
      

      使用位置 $ 运算符将新对象推送到匹配产品元素中的数组中:

      Partner.update({_id: req.body.partnerId), 'products.name': req.body.dataProduct.name }, { $push: { 'products.$.campaignList': { name: 'new campaign' }}})
      

      参考https://docs.mongodb.com/manual/reference/operator/update/positional/

      【讨论】:

      • 我直接通过 Robomongo 在 Mongoose 之外进行了测试,并按预期进行了更新。也许还有其他一些细节阻止了这项工作?也许 req.body.partnerId 或 req.body.dataProduct.name 引用有问题?
      【解决方案3】:

      试试这个:

      router.post('/addProduct', function (req, res) {
              Partner.findOneAndUpdate({ _id: req.body.partnerId }, { $push: { "products": { name: req.body.dataProduct.name, $push: {"campaignList": {name: req.body.name}} } } }, { safe: true }, function (err, response) {
                  if (err) throw err;
                  res.json(response);
              });
          });
      

      希望对你有帮助

      【讨论】:

      • 此代码将添加新的product 而不是将campaignList 添加到现有的
      猜你喜欢
      • 2019-10-01
      • 2019-01-18
      • 1970-01-01
      • 2017-04-20
      • 2013-07-31
      • 2020-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多