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

时间:2016-06-16 17:58:42

标签: javascript node.js mongodb

我知道如何使用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 - 通常情况下,但我想肯定地说:)

3 个答案:

答案 0 :(得分:1)

你最好的选择是定义Schema&该广告系列的模型,并使用_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的数组。

答案 1 :(得分:0)

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

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/

答案 2 :(得分:-1)

试试这个:

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

我希望它可以帮助你