Alex Polkhovsky
Alex Polkhovsky

Reputation: 3360

Update searching by ObjectId in an array of objects

Business schema:

var BusinessSchema = new Schema({
    owners: {type: Array},
    templates:[{
        _id : ObjectId,
        title : String,
        path : String,
        custom_navigation : Boolean
    }]
});

Business collection looks like this:

{"owners" : [
        ObjectId("522fa2d61685d3f4ce000002")
    ],
    "templates" : [
        {
            "_id" : ObjectId("524c3bacc7ba62c549000004"),
            "custom_navigation" : true
        },
        {
            "_id" : ObjectId("524c3bacc7ba62c549000005")
        },
        {
            "_id" : ObjectId("524c3bacc7ba62c549000006")
        }
    ]}

Function to update a particular template stored in templates array:

        var Business = require('../models/business.js');

        Business.update({'owners' : req.user._id, "templates._id" : req.body._id}, {
            $set : {"templates.$.custom_navigation" : req.body.custom_navigation}
        },
        function(err, numUpdated){
            console.log(numUpdated);
            if(numUpdated > 0){
                res.json(200, req.body);
            }else{
                res.json(404);
            }
        });

When I output the search parameter for update function, I see this:

{ owners: 522fa2d61685d3f4ce000002,
  'templates._id': '524c3bacc7ba62c549000004' }

Note, that Mongoose seems to recognize req.user._id as ObjectId, but req.body._id is passed as a string. I tried converting it to ObjectId with no results. The update statement always updates the first item in templates array, no matter what templates._id is set to.

Upvotes: 0

Views: 181

Answers (1)

Sriharsha
Sriharsha

Reputation: 2443

You need to search by the Object id and merely not by req.body._id (I am guessing it is a interger)

var templateId = require('mongoose').Types.ObjectId;
Business.update({'owners' : req.user._id, "templates" : {$elemMatch :{ _id: new templateId(req.body._id)}}},     
....

Upvotes: 0

Related Questions