query and populate a DBRef in a subDocument

45 views
Skip to first unread message

Jonas Garbuio

unread,
Apr 13, 2018, 9:24:17 AM4/13/18
to Mongoose Node.JS ODM
Hi.

I have a symfony App using Doctrine ODM and I'd like to make a little node script to do some changes in DB.

With this, I have a CHapter Document with this architecture:
{
...
    pages
: [
       
{
             
...
             image
: DBRef to files.files
       
}
   
]
}


And in node with mongoose I'd like to populate pages.image when I findById a chapter but I can't get it to work.

Here are my schemas : 
//instantiate mongoose-gridfs
var gridfs = require('mongoose-gridfs')({
    collection
:'files',
    mongooseConnection
: mongoose.connection
});


//Files = gridfs.model;
var FilesSchema = gridfs.schema;


FilesSchema.add({
    _id
: Schema.Types.ObjectId,
    name
: String,
    mime
: String,
    filename
: String,
    type
: String
});


Files = mongoose.model('Files', FilesSchema);


var pageSchema = Schema({
    order
: Number,
    image
: { type: Schema.Types.ObjectId, ref: 'Files' },
    scrambled
: Boolean
});


var ChapterSchema = Schema({
    _id
: Schema.Types.ObjectId,
    pages
: [pageSchema]
});


var Chapter = mongoose.model('Chapter', ChapterSchema, "Chapter");

and my find

Chapter.findById(chapterId)
       
.populate('pages.image')
       
exec(...

and then I have this error : { CastError: Cast to ObjectId failed for value "DBRef ...
complete message here : https://pastebin.com/8n54Dhzt

I thought about creating a model Image with the DBRef property ($id, $db, $ref) and use the ObjetID Types on the $id property but I'm not sure it's a good idea.

Reply all
Reply to author
Forward
0 new messages