猫鼬不参考新保存的文档填充以前保存的文档

Mongoose not populating previously saved document with reference to newly saved document

全部。

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

这是我的公司和用户架构:

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": "a$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

但是公司的 users 数组没有填充用户的 id,.exec 函数中的 console.log 打印'TEST53's users now includes'.

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

有什么明显的我遗漏的东西吗?在此先感谢您的任何建议!

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

试试这个:

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(...) 调用。