0

I have a self reference in mongoose like this :

var wordSchema = new mongoose.Schema({
        content : String,
        country: [{type: mongoose.Schema.Types.ObjectId, ref: 'Country'}],
        trad: {
            words: [{
                _id: { type: mongoose.Schema.Types.ObjectId, ref: 'Word' }

            }]
        }

    });

I want to get back the attribute content of my model with a find :

 Word.find({ content:regex, country:'5464dcee1874048e2c623389' }).populate('trad.words').exec(function (err, words) {
        if (!err) {
            res.json(words);
        } else {
            console.log(err);
        }
    });

Here is the results I get :

_id: "5468d91c6481cd063033a4d0"
content: "content"
country: [5464ddd226e63fad2c5aa053]
trad: {words:[{_id:5468d91c6481cd063033a4cf}]}
words: [{_id:5468d91c6481cd063033a4cf}]
0: {_id:5468d91c6481cd063033a4cf}
_id: "5468d91c6481cd063033a4cf"

I don't understand why it's not return me others attribute in the subDocument word.. Can you help me understand what I am doing wrong?

Thanks,

Maxime

user3653664
  • 37
  • 10

1 Answers1

0

There are more than one trad? So, set the path populate('countries trad.words') as below:

var wordSchema = new mongoose.Schema({
        content : String,
        countries: [{type: mongoose.Schema.Types.ObjectId, ref: 'Country'}],
        trad: [{
            _id: mongoose.Schema.Types.ObjectId,
            words: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Word' }]
        }]
    });

Otherwise, you not need of trad field. So, set the path populate('countries trad_words') as below:

var wordSchema = new mongoose.Schema({
        content : String,
        countries: [{type: mongoose.Schema.Types.ObjectId, ref: 'Country'}],
        trad_words: [{type: mongoose.Schema.Types.ObjectId, ref: 'Word'}]
    });
  • Many, Many thanks Fernando. Just a little question : How do I add a new trad so ? I try words.trad.push(traduction); It return me Cannot call method 'push' of undefined.. (based of the first schema you propose to me) – user3653664 Nov 17 '14 at 09:49
  • Now, with your schema defined, it's easy. For more information, consult this link: http://mongoosejs.com/docs/subdocs.html If you can't resolve, write here again. – Fernando Santucci Nov 17 '14 at 23:30