Reputation: 465
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 ?
Upvotes: 1
Views: 1876
Reputation: 465
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);
});
});
Upvotes: 1
Reputation: 740
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.
Upvotes: 1