Mongoose未参考新保存的文档

时间:2015-07-21 13:27:50

标签: mongodb express mongoose mongoose-populate

所有。

我正在编写一个MEAN堆栈应用程序,使用带有Node / Express的Mongoose(4.0.6)与MongoDB进行交互,当我稍后保存现有文档应该有参考的新文档时,我遇到了填充已保存文档的困难至。具体来说,在应用程序中,我让用户在为该公司创建管理员帐户之前创建公司实例,因此当用户将他/她自己注册为管理员时,我希望公司文档用其填充其用户数组新用户。

以下是我公司和用户的模式:

... user.js的

var mongoose = require('mongoose');
var Schema   = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;

var userSchema = new Schema({
  first_name:      { type: String, required: '{PATH} is required!' },
  last_name:       { type: String, required: '{PATH} is required!' },
  username:        { type: String, required: '{PATH} is required!', lowercase: true, unique: true },
  password:        { type: String, required: '{PATH} is required!' },
  roles:           { type: [String] },
  company:         { type: ObjectId, ref: 'Company', required: true },
  db_permissions: [{ type: ObjectId, ref: 'DataConnection' }],
  created_by:      { type: ObjectId, ref: 'User' }, 
  created_at:      { type: Date, default: Date.now },
  updated_at:     [{ type: Date, default: Date.now }]
});

var User = mongoose.model('User', userSchema);

module.exports = {
  User: User
};

... Company.js

var mongoose = require('mongoose');
var Schema   = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;

var companySchema = new Schema({
  name:              { type: String, uppercase: true, required: '{PATH} is required!', unique: true }, 
  industry:          { type: String, required: '{PATH} is required!' }, 
  phone:             { type: String, required: '{PATH} is required!' },
  address_line_1:    { type: String, uppercase: true, required: '{PATH} is required!' },
  address_line_2:    { type: String, uppercase: true },
  city:              { type: String, uppercase: true, required: '{PATH} is required!' },
  state_prov:        { type: String, uppercase: true, required: '{PATH} is required!' },
  postal_code:       { type: String, required: '{PATH} is required!' },
  country:           { type: String, required: '{PATH} is required!' }, 
  logo_url:            String,
  users:            [{ type: ObjectId, ref: 'User' }],
  data_connections: [{ type: ObjectId, ref: 'DataConnection' }],
  created_at:        { type: Date, default: Date.now },
  updated_at:       [{ type: Date, default: Date.now }]
});

var Company = mongoose.model('Company', companySchema);

module.exports = {
  Company: Company
};

以下是我的控制器中的代码:

User.create(userData, function(err, user) {
  if(err) {
    if(err.toString().indexOf('E11000') > -1) {
      err = new Error('Duplicate email');
    }
    res.status(400);
    return res.send({ reason:err.toString() });
  }
  console.log('company id: ' + user.company);
  Company.findById(user.company)
    .populate({path: 'users'})
    .exec(function (err, company) {
      if (err) return handleError(err);
      console.log(company.name + '\'s users now includes ' + company.users);
    });   
  res.send(user);

公司(例如TEST53)使用空用户数组正确保存到数据库:

{
    "_id": "55ae421bf469f1b97bb52d5a",
    "name": "TEST53",
    "industry": "Construction",
    "phone": "2352626254",
    "city": "GDFGD",
    "country": "United States",
    "address_line_1": "DSGDFGH",
    "state_prov": "GF",
    "postal_code": "45645",
    "logo_url": "",
    "__v": 0,
    "updated_at": [
        "2015-07-21T12:59:07.609Z"
    ],
    "created_at": "2015-07-21T12:59:07.597Z",
    "data_connections": [],
    "users": []
}

然后,当我创建用户时,它会正确保存:

{
    "_id": "55ae4238f469f1b97bb52d5b",
    "username": "test53@test.com",
    "password": "$2a$12$ZB6L1NCZEhLfjs99yUUNNOQEknyQmX6nP2BxBvo1uZGlvk9LlKGFu",
    "company": "55ae421bf469f1b97bb52d5a",
    "first_name": "Test53",
    "last_name": "Admin",
    "__v": 0,
    "updated_at": [
        "2015-07-21T12:59:36.925Z"
    ],
    "created_at": "2015-07-21T12:59:36.550Z",
    "db_permissions": [],
    "roles": [
        "admin"
    ]
}

我可以看到正确的ObjectId打印到user.company的控制台:

company id: 55ae421bf469f1b97bb52d5a

但该公司的用户数组不会填充用户的ID,并且.exe​​c函数内的console.log打印'TEST53的用户现在包括'。

我已经尝试了几种方法来连接它,仅使用'users'而不是{path:'users'},编写一个将用户推入数组的函数,使用.run而不是.exec,但到目前为止没有成功。

有什么明显的东西我不见了吗?提前感谢任何建议!

1 个答案:

答案 0 :(得分:2)

您实际上并没有将用户添加到公司。

试试这个:

Company.findById(user.company, function (err, company) {
  if (err) return handleError(err);

  // Add the user to the company's list of users.
  company.users.push(user);

  // Need to save again.
  company.save(function(err) {
    if (err) return handleError(err);
    console.log(company.name + '\'s users now includes ' + company.users);
  });
});
res.send(user);

在我看来,您要做的就是更新Company模型以添加用户,而不是实际使用(填充的)Company文档作为响应,所以我离开了另外Company.findById(...).populate(...)来电。