繁体   English   中英

如何使用Node.js将对象添加到MongoDB中另一个集合中的集合

[英]How to add object to collection inside another collection in MongoDB using Node.js

我知道如何使用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 这就是为什么不在上面的架构中。 然而我将它们从FrontEnd发送到BackEnd作为req.parameter - 通常是我想说的肯定:)

您最好的选择是打赌自己定义广告系列的架构和模型,然后使用_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数组。

首先匹配所需的产品阵列位置。 您可以通过测试一个简单的查找来确认:

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

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

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/

尝试这个:

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

我希望它可以帮助你

暂无
暂无

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

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