1

I have recently begun using MongoDB with Mongoose and have what probably seems like a straightforward question. I have two models so far, a User and a post. Posts are owned by a user, this is referenced by the ObjectId. Here are the models:

Post

var mongoose = require('mongoose');

var PostSchema = new mongoose.Schema({

  text: String,
  stars: { type: Number, default: 0 },
  score: { type: Number, default: 0 },
  user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', default: '554cb70669234d6f04f425a2' }
});

PostSchema.methods.addstar = function(cb) {
  this.stars += 1;
  this.save(cb);
};

mongoose.model('Post', PostSchema);

User

var mongoose = require('mongoose');
var crypto = require('crypto');
var jwt = require('jsonwebtoken');

var UserSchema = new mongoose.Schema({
  username: {type: String, lowercase: true, unique: true},
  hash: String,
  salt: String
});

mongoose.model('User', UserSchema);

When I want to use the data on the HTML page with angular I am trying to access the username by using:

{{ post.user.username }}

However this isn't yielding any results. Do I need to make a separate get request with the userid, or is their a more intuitive way?

As mentioned, I understand this question may seem quite basic. I am just learning Mongo, and have previously worked with Rails Databases, where a lot of functionality is obscured.

Any ideas ?

amdixon
  • 3,814
  • 8
  • 25
  • 34
Phil Brockwell
  • 456
  • 5
  • 22

2 Answers2

1

Maybe the answer is in here: Referencing another schema in Mongoose

Summary:

when you make your query, you can populate references like this:

Post.findOne({_id: 123})
.populate('user')
.exec(function(err, post) {
    // do stuff with post
});

So before you execute the find, you tell mongo to populate the user.

Community
  • 1
  • 1
tuvokki
  • 720
  • 1
  • 10
  • 18
  • Thank you @tuvokki. Thats works for one post. In my initial get request I'm getting all of the posts and want to populate each ones username. This code isn't working: `Post.find() .populate('user', 'username') .exec(function (err, posts) { if(err){ return(err); } res.json(posts); });` – Phil Brockwell May 08 '15 at 15:10
1

The following code returns all of the posts with the users populated for each one. I had forgotten to include the empty object inside the method call for Post.find().

router.get('/posts', function (req, res, next) {
  Post.find({})
  .populate('user')
  .exec(function (err, posts) {
    if(err){ return(err); }
    res.json(posts);
  });
});
Phil Brockwell
  • 456
  • 5
  • 22