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' }
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With