2

How can I add object to my nested Array in PartnerSchema?

I separate documents, because in the future there will be more of nested arrays.

This is my schema:

var productSchema = new mongoose.Schema({
    name: String
});

var partnerSchema = new mongoose.Schema({
    name: String,
    products: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Product'
        }]
});

module.exports = {
    Partner: mongoose.model('Partner', partnerSchema),
    Product: mongoose.model('Product', productSchema)
}

And this is my backend:

var campSchema = require('../model/camp-schema');

router.post('/addPartner', function (req, res) {
    new campSchema.Partner({ name : req.body.name }).save(function (err, response) {
        if (err) console.log(err);
        res.json(response);
    });
});

router.post('/addProduct', function (req, res) {
    campSchema.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);
    });
});

I can add Partner by using /addPartner and it works fine.

Problem is with second function /addProduct I can't add Product to Array in Partner Schema. I have an error: CastError: Cast to undefinded failed for value "[object Object]" at path "products"

1 Answer 1

3

Since the products field in Partner model is an array that holds _id refs to the Product model, you are supposed to push an _id to the array, not an object hence Mongoose complains with an error.

You should restructure your code to allow the saving of the Product _id ref to the Partner model:

router.post('/addProduct', function (req, res) {
    var product = new campSchema.Product(req.body.dataProduct);

    product.save(function (err) {
        if (err) return throw err;        
        campSchema.Partner.findByIdAndUpdate(
            req.body.partnerId,
            { "$push": { "products": product._id } },
            { "new": true },
            function (err, partner) {
                if (err) throw err;
                res.json(partner);
            }
        );
    });
});
Sign up to request clarification or add additional context in comments.

8 Comments

What about name? This code only adding products with id. I have to add also req.body.dataProduct.name to name field in products
There's no need to add the name because Mongoose automatically adds that for you when you do the population. You need to understand the notion of Mongoose population, I suggest you read more here
{ "_id" : ObjectId("576a4ed4318781680dc3e57f"), "name" : "examplePartner", "products" : [ ObjectId("576a5e54e8b3585818502fc4") ], "__v" : 0 } As you can see in products array is only ID. Without name...
That is what it is supposed to be, just an array with _ids. If you understood correctly what Mongoose populate does then you will know it will automatically create the document for you behind the scenes when you are querying the collection. In the instance above, you are saving the data so there is no need to save it as an object because you have defined it in your schema to use the ref property. I encourage you to have a read about the topic populate more so that you get a better understanding.
Ok i understood. Now I wonder if it was a good idea to separate documents. Because how will I display products to specific partner. Before when I had product inside partner, was easy - li(ng-repeat="product in partner.products") a(href="#") {{ product.name }} so maybe I shouldn't separate these documents?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.