简体   繁体   中英

How to save nested mongoDB properties with mongoose?

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 ... */
  },
});

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'
  }
});

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