如何使用猫鼬保存嵌套的mongoDB属性



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

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

您的架构很好,但您无法像在第二个代码示例中那样在新对象的根目录上定义嵌套属性,而无需引用它们。它应该看起来像这样:

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

最新更新