Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save populated Document?

Is it possible to save a populated document?

I am trying to do:

var Group = new Db['Group']();
for (var i=0; i<50; i++)
    Db.Members.push({ User: { _id: "521014731e27b1b008000002"}, pseudo: 'John' });
Group.save();

Schemas

var GroupSchemaModel = {
    Members: [{
        User: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
        updated_at: { type: Date, required: true, default: Date.now }
    }]
};

I get the error

{ message: 'Cast to ObjectId failed for value "[object Object]" at path "User"',
name: 'CastError',
type: 'ObjectId',
value: { _id: '521014731e27b1b008000002' },
path: 'User' }
like image 636
Ludo Avatar asked Aug 24 '13 20:08

Ludo


1 Answers

This:

User: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },

Tells mongoose that User field will be a collection of references of type ObjectId pointing to another collection.

You, on the other hand, are trying to insert an object there:

Db.Members.push({ User: { _id: "521014731e27b1b008000002"}, pseudo: 'John' });

Mongoose tries to cast it to ObjectId and fails. That's apart from the fact that pseudo field isn't in the group schema.

Try this instead:

Db.Members.push({User: mongoose.Types.ObjectId("521014731e27b1b008000002"), updated_at: whatever});
like image 183
soulcheck Avatar answered Nov 16 '22 00:11

soulcheck