如何使用mongoose保存嵌套的mongoDB属性?

时间:2016-02-15 09:46:08

标签: javascript node.js mongodb express mongoose

假设我想创建一个具有嵌套属性的用户模式:

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

现在,如果我想将用户保存在像ExpressJs这样的nodejs框架中,我会像这样保存它:

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

我想知道我的架构是否良好,或者是在根中创建所有属性的最佳实践,如下所示:

var userSchema = new mongoose.Schema({
  username: { type: String, unique: true, lowercase: true },
  firstName: { type: String },
  /* ... some other properties ... */
  },
});

1 个答案:

答案 0 :(得分:1)

您的架构很好,但是您不能像在第二个代码示例中那样在新对象的根上定义嵌套属性而不引用它们。它应该是这样的:

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

虽然我建议像这样正确地嵌套它

var user1 = new User(
{
  username: 'Zildjian',
  profile: {
    firstName:'test'
  }
});