Reputation: 2357
Let say that i want to make a user schema with nested properties:
var userSchema = new mongoose.Schema({
username: { type: String, unique: true, lowercase: true },
/* ... some other properties ... */
profile: {
firstName: { type: String, default: '' },
/* ... some other properties ... */
},
});
module.exports = mongoose.model('User', userSchema);
Now if i want to save a user in a nodejs framework like ExpressJs, i will save it like so:
var user = new User({
username: req.body.username,
profile.firstName: req.body.firstName /* this is what i want to achive here */
});
user.save(function(err) {
if (!err) {
console.log('User created');
}
});
And i want to know if my Schema is good, or it's best practice to make all the properties in the root, as this:
var userSchema = new mongoose.Schema({
username: { type: String, unique: true, lowercase: true },
firstName: { type: String },
/* ... some other properties ... */
},
});
Upvotes: 0
Views: 237
Reputation: 7870
Your schema is good, but you cant define nested properties on the root of a new object as you did in your second code sample without quoting them. It should look like this:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var User = mongoose.model('User', {
username: String,
profile: {
firstName: String
}
});
var user1 = new User(
{
username: 'Zildjian',
'profile.firstName':'test'
});
user1.save(function (err) {
if (err) // ...
console.log('meow');
process.exit(0);
});
Although I would recommend nesting it properly like this
var user1 = new User(
{
username: 'Zildjian',
profile: {
firstName:'test'
}
});
Upvotes: 1