简体   繁体   中英

Error in referencing custom schemas in node.js app

Node.js newbie here... I have a two schemas and I am referencing one within the other.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

/*Model for user settings */

var SettingsSchema = new Schema({
shoppingDay: {type: String, default : "Friday"},
shoppingFrequency : {type: String, default : "weekly"},
reminderEmails : {type: Boolean, default : true}
});

module.exports = mongoose.model('Settings', SettingsSchema);

and

var mongoose = require('mongoose');
var Schema = mongoose.Schema;    
var Settings = require('./Settings.js');
var SettingsSchema = Settings.Schema;   

/*Model for user settings */
var UserTrendSchema = new Schema({
    email : String,    
    settings  : SettingsSchema
},
{collection : 'UserTrends'});

module.exports = mongoose.model('UserTrend', UserTrendSchema);

I am running into this error

throw new TypeError('Invalid value for schema path `'+ prefix + i +'`');

but if I make it an array, it works.

settings  : [SettingsSchema]

I don't want it to be an array. Just a single instance of settings. All the examples I see use their custom types as arrays.

I also tried

settings  : {type: Schema.Types.ObjectId, ref: 'Settings'}

but it just creates an entry in the DB with an object id and does not include the default values

 "settings": {
    "$oid": "54ccfdcb5926074c1d53d02f"
},

What's the best way to do this?

If you dont want setting to be an Array you can keep settings as Object and refer it to the Settings model. while fetching you can populate the settings.

Changes :

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

/*Model for user settings */

var SettingsSchema = new Schema({
shoppingDay: {type: String, default : "Friday"},
shoppingFrequency : {type: String, default : "weekly"},
reminderEmails : {type: Boolean, default : true}
});

module.exports = mongoose.model('Settings', SettingsSchema);

var mongoose = require('mongoose');
var Schema = mongoose.Schema;    

/*Model for user settings */
var UserTrendSchema = new Schema({
email : String,    
settings  : {type: Schema.Types.ObjectId, ref: 'Settings'} // refers to Settings Model.
},
{collection : 'UserTrends'});

module.exports = mongoose.model('UserTrend', UserTrendSchema);

Where settings will be objectId and can be populated.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM