【问题标题】:Mongoose populate not populating猫鼬填充不填充
【发布时间】:2016-10-10 15:07:06
【问题描述】:

我正在尝试填充我的用户汽车库存。所有汽车在创建时都附加了一个 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
}

任何建议都会很棒!谢谢!

【问题讨论】:

    标签: javascript node.js mongodb mean-stack mongoose-populate


    【解决方案1】:

    Populate in Mongoose 目前仅适用于 _id's,尽管有一个 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')
    

    【讨论】:

    • 所以我需要在我的汽车模型中添加一个 _id 字段?当您保存到数据库时,Mongo 会自动为您创建它。它们不是按照我目前拥有它们的方式连接起来的吗?我认为 userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, and inventory: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Car' }] 正在这样做。
    • JuniorSauce 您将“汽车”中的哪个字段存储在该数组中?应该是_id
    • User 模型中的 inventory 字段应该是这样做的。
    • JuniorSauce,如果您没有正确地将汽车保存在库存中,则不会。这就是我猜的问题所在。
    • 哦,我以为填充会通过获取 userId 来做到这一点。所以我需要以某种方式将汽车保存到库存中。这很混乱哈哈。感谢您的帮助。
    猜你喜欢
    • 2015-07-13
    • 2015-07-13
    • 2020-01-17
    • 2021-05-06
    • 2019-06-05
    • 2019-09-16
    • 2021-05-03
    • 2021-01-09
    相关资源
    最近更新 更多