猫鼬填充不填充

Mongoose populate not populating

我正在尝试填充我的用户的汽车库存。所有汽车在创建时都附加了一个 userId,但是当我去填充库存时它不起作用并且我没有收到任何错误。

这是我的模型:

User.js

let UserSchema = mongoose.Schema({
  username: {
    type: String,
    required: true,
    unique: true
  },
  password: {
    type: String,
    required: true
  },
  inventory: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Car' }]
});

let User = mongoose.model('User', UserSchema);
models.User = User;

Cars.js

let CarSchema = mongoose.Schema({
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },
  make: {
    type: String,
    required: true
  },
  model: {
    type: String,
    required: true
  },
  year: {
    type: String
  }
});

let Car = mongoose.model('Car', CarSchema);
models.Car = Car;

这是填充代码:

router.route('/users/:user/inventory').get((req, res) => {
    User.findById(userId)
      .populate('inventory') 
      .exec((err, user) => {
        if (err) {
          console.log("ERRROORRR " + err)
          return res.send(err);
        }

        console.log('Populate ' + user)
        res.status(200).json({message: 'Returned User', data: user});
      });
    });
  };

这是汽车对象在数据库中的样子:

{
  "_id": ObjectId("5759c00d9928cb581b5424d0"),
  "make": "dasda",
  "model": "dafsd",
  "year": "asdfa",
  "userId": ObjectId("575848d8d11e03f611b812cf"),
  "__v": 0
}

任何建议都很好!谢谢!

在 Mongoose 中填充目前仅适用于 _id,但有 long-standing issue 可以改变这一点。您需要确保您的 Car 模型有一个 _id 字段,并且 User 中的 inventory 字段是这些 _id 的数组。

let CarSchema = new mongoose.Schema(); //implicit _id field - created by mongo
// Car { _id: 'somerandomstring' }

let UserSchema = new mongoose.Schema({
  inventory: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Car'
  }]
});
// User { inventory: ['somerandomstring'] }

User.populate('inventory')