Gistflow

Tagged #mongodb
50a1c1f2651b478f8cb8bff34ad41515?d=https%3a%2f%2fidenticons.github.com%2f50a1c1f2651b478f8cb8bff34ad41515

Need some help in mongo design

I need to store lots of data and with each entry there is a Facebook user id to whom data belongs to. What is the best way to store this in #mongodb?

Is one collection with entries like this will be fine?

{
  "stuff": { ... },
  "id": "<facebook-user-id>"
}

Later I will need this do display his own stuff to the logged in user.

03 Feb 2013
50a1c1f2651b478f8cb8bff34ad41515?d=https%3a%2f%2fidenticons.github.com%2f50a1c1f2651b478f8cb8bff34ad41515

Mongoose populate

Simple example for the mongoose 'populate' feature: referencing objects from each other.

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

mongoose.connect('mongodb://localhost/testy2');

var UserSchema = new Schema({
    name: String
});

var MovieSchema = new Schema({
    title: String,
    tags: [new Schema({
        _name: {type: Schema.ObjectId, ref: 'Tag'},
        _owner: {type: Schema.ObjectId, ref: 'User'}
    })]
});

var TagSchema = new Schema({
    name: String
});

var Tag = mongoose.model('Tag', TagSchema),
    User = mongoose.model('User', UserSchema),
    Movie = mongoose.model('Movie', MovieSchema);

User.create({name: 'Johnny'}, function(err, johnny) {
    Tag.create({name: 'drama'}, function(err, drama) {
        Movie.create({'title': 'Dracula', tags:[{_name: drama._id, _owner: johnny._id}]}, function(err, movie) {

            Movie.findById(movie).populate('tags._owner').run(function(err, movie) {
                console.log(movie.tags[0]._owner);
            });
        });
    });
});

#javascript #node #mongoose #mongodb

03 Apr 2012