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

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

最佳答案

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

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

关于javascript - 如何使用 mongoose 保存嵌套的 mongoDB 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35406012/

相关文章:

php - 蒙戈日期转换

javascript - 编写处理另一个函数输出的PHP函数时要使用哪种设计模式?

javascript - Sencha Touch 2 : Ext. Msg.show 并点击任意位置隐藏

node.js - 从 Node (Express) 处理 MongoDB 连接问题

javascript - 错误 : Connection timeout at SMTPConnection. _formatError

mongodb .net 驱动程序 V2 : How to do array operations

javascript - 防止 jQuery 跳到底部(使用 fadeIn 时)

javascript - Form.target = window.opener.name 不起作用

javascript - 无法将 npm 升级到 npm@latest Mac

mysql - 未创建 Sequelize 外键(对于 MySQL)