猫鼬人口不足

时间:2016-06-09 19:40:14

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

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

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

1 个答案:

答案 0 :(得分:2)

在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')