Anon
Anon

Reputation: 45

Adding a document to a document (subdocs) does not work

Unfortunately, but the subdocument in mongoose does not work and I do not really know why:

...
mongoose.connect('mongodb://[email protected]:59676/zxcv');
var Schema = mongoose.Schema;
 
var entrySchema = Schema({
    title: String,
    img: String,
    info: String,
    link: String
}, {collection: 'xxx'});
 
var userDataSchema = Schema({
  name: String,
  password: { type: String, select: false},
  birth: Number,
  followers: [{ "name": String}],
  entry: [entrySchema]
}, {collection: 'yyy'});
 
var UserData = mongoose.model('UserData', userDataSchema);
var entry = mongoose.model('entry', entrySchema);
 
app.get('/:user', function(req, res) {
    UserData.findOne( {'name': req.params.user}, function(err, user) {
        if (err)
            res.send(err);
        res.json(user);
    });
});

This code returns data from the userDataSchema scheme and empty entry: []. I can query userDataSchema and entrySchema separately and return correct data, but it does not work together. Where do I make a mistake? By default, I would like to dynamically add all collections (name in followers) to my schema.

Upvotes: 2

Views: 55

Answers (2)

YouneL
YouneL

Reputation: 8369

var entrySchema = new Schema({
                  ^^^
    title: String,
    img: String,
    info: String,
    link: String
});

Edit: when you declared entrySchema with {collection: 'xxx'} you force mongoose to create a separete collection with name of xxx, that's why you should reference the entrySchema inside userDataSchema as described by chridam's answer, or remove collection option: {collection: 'xxx'}

Upvotes: 1

chridam
chridam

Reputation: 103435

You need to re-define your schemas to use populate() as:

var mongoose = require('mongoose');
var Schema = mongoose.Schema; 

var entrySchema = Schema({
    title: String,
    img: String,
    info: String,
    link: String
}, {collection: 'xxx'});

var userDataSchema = Schema({
    name: String,
    password: { type: String, select: false },
    birth: Number,
    followers: [{ "name": String}],
    entry: [{ type: Schema.Types.ObjectId, ref: 'entry' }]
}, {collection: 'yyy'});


var UserData = mongoose.model('UserData', userDataSchema);
var entry = mongoose.model('entry', entrySchema);

app.get('/:user', function(req, res) {
    UserData.findOne({'name': req.params.user})
        .populate('entry')
        .exec(function(err, user) {
            if (err)
                res.send(err);
            res.json(user);
        });
});

This works given that you have actually saved the references to the entry model as _ids in the userData collection.

For in-depth explanation of how the above works, consult the docs.

Upvotes: 1

Related Questions