简体   繁体   English

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

[英]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: 现在,如果我想将用户保存在像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');
  }
});

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM