使用ObjectId以外的SchemaTypes(Mongoose)

时间:2014-05-06 14:30:41

标签: node.js mongoose

我对node.js和mongoose相对较新,所以我一直试图让人口为猫鼬工作。根据官方的mongoose文档,字符串可以用作参考:

  

注意:ObjectId,Number,String和Buffer可用作refs。

基于此,我一直在尝试填充String类型的字段,而不是ObjectId。但是,每次我尝试这样做时,都会遇到CastError:

  

CastError:对于值" testuser",转换为ObjectId失败在路径" _id"

如果有帮助,请点击我的代码:

/=============== 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 }
});

基本上,用户的设置是在创建用户后创建的。

感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:3)

虽然您可以使用ObjectId以外的类型作为参考,但参考号不能引用_id以外的任何字段。为此,您必须将_id UserSchema声明为String,并将其值设置为您提供的相同值username

var UserSchema = new mongoose.Schema({
    _id: { type: String },
    _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 } 
});