Reputation: 6263
I'm fairly new to this, so bear with me, however I have 2 collections. One called photos and another called users.
In Node, I am taking the data and putting it into my MongoDB using mongoose. I've got this working fine with my Schema:
var picSchema = new Schema({
uid: String,
pid: String,
oFile: String
});
What I want to do though is for the uid, I want to add the ObjectId for the user uploading the photo. I can pass this as a String, however I thought that I would have had to have the field set as an ObjectId, but seems I cannot do this?
Unless I am missing something, I might as well just add the username in there and use that as a reference?
Upvotes: 5
Views: 13844
Reputation: 2253
Use mongoose.Schema.Types.ObjectId
to populate the field with an ObjectId. In this case, you would use User
(or whatever the name of your User schema is).
var picSchema = new Schema({
uid: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
pid: String,
oFile: String
});
Further to this, you can also use the Mongoose method Populate
if you wish to expand the User document within a Pic
document. For example:
Pic.find({})
.populate('uid')
.exec(function(err, pic) {
console.log(pic);
// do something
});
Upvotes: 2