I am relatively new to node.js and mongoose, so I've been trying to get population working for mongoose. According to the official mongoose documentation, Strings can be used as refs:
Note: ObjectId, Number, String, and Buffer are valid for use as refs.
Based on this, I've been trying to populate a field that is of type String, rather than ObjectId. However, every time I try to do so, I get a CastError:
CastError: Cast to ObjectId failed for value "testuser" at path "_id"
If it helps, here's my code:
/=============== In user.js ===============/
var UserSchema = new mongoose.Schema({
_username: { type: String, required: true, unique: true },
password: { type: String, required: true },
date_created: { type: Date, required: true, default: Date.now() },
last_accessed: { type: Date, required: true },
admin_access: { type: Boolean, required: true }
});
UserSchema.post('save', function(user) {
// Settings Model
var Settings = require('./settings');
var setting = new Settings.SettingsModel({
_user: user._username
});
setting.save(function(err) {
if (err) throw err;
console.log('Successfully created settings for user: ' + setting);
Settings.SettingsModel.findOne({ _user: user._username }, function(err, setting) {
Settings.SettingsModel.populate(setting, { path: '_user' }, function(err, setting) {
if (err) throw err;
console.log('User of setting is ' + setting._user);
});
});
});
});
/=============== In settings.js ===============/
var SettingsSchema = new mongoose.Schema({
_user: { type: String, ref: 'User', unique: true },
defaultCurrency: { type: String, default: 'USD', required: true },
secondaryCurrency: { type: String }
});
Basically, settings for a user is created after a user has been created.
Any help is appreciated. Thanks!
_id
", you can have a look at this question : stackoverflow.com/q/19287142/488666 – Frosty Z