Problem with a array of objects (or subdoc)

1,805 views
Skip to first unread message

alem...@gmail.com

unread,
Dec 17, 2015, 5:04:00 AM12/17/15
to Mongoose Node.JS ODM
Hello everyone, I encounter a problem that prevents me from updating a field which is an array of objects.

Here's the schema:
var BSchema = new mongoose.Schema({
       owner
: {type: mongoose.Schema.Types.ObjectId, ref: 'CollectionA'},
       content
: [
               
{
                       item
: {type: mongoose.Schema.Types.ObjectId, required: true, ref: 'CollectionC'},
                       amount
: {type: Number, required: true}
               
}
       
]
});

This is the code used to update the content:
router.route('/')
       
.put((req, res) => {
               
//content being PUT here is only ids, need to translate back to object ref first
               
var newcontent = req.body.content;
                newcontent
.forEach((e, i, a) => a[i].item = new mongoose.Schema.Types.ObjectId(e.item));
               
BModel.findByIdAndUpdate(req.session.cart._id, {content: newcontent}, (e, c) => {
                       
...
               
}
       
}

Whatever the update parameter is (tried { $set: { content: newcontent} }, { $push: { content: newcontent} }), all give me this same error:
{
   
[CastError: Cast to embedded failed for value "[object Object]" at path "content"]
    message
: 'Cast to embedded failed for value "[object Object]" at path "content"',
    name
: 'CastError',
    kind
: 'embedded',
    value
: {
        item
: ObjectId {
            path
: '5647142b8706599779e15368',
            instance
: 'ObjectID',
            validators
: [],
            setters
: [],
            getters
: [],
            options
: undefined,
            _index
: null
       
},
        amount
: 3
   
},
    path
: 'content',
    reason
: undefined
}

As you can see the value should conform to the embedded doc definition in the schema.
This is so cryptic that I can't understand how this happened.

Whatever document I can find is about how to update array by inserting elements, what I want is replace that array with a new one.
What is the proper way to do this?

alem...@gmail.com

unread,
Dec 21, 2015, 12:41:41 AM12/21/15
to Mongoose Node.JS ODM
Removing the ObjectId casting fixes the problem. I wonder why passing a ObjectId object is wrong.
Reply all
Reply to author
Forward
0 new messages