javascript - Mongoose 填充不填充

标签 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
}

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

最佳答案

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

关于javascript - Mongoose 填充不填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37734827/

相关文章:

node.js - socket.io 广播不适用于 React

javascript - 如何在每个午夜自动更新 MongoDB 集合?

mongodb - 如何诊断周期性 MongoDB 缓慢?

javascript - 查找 'unknown' 形式的所有单选按钮

javascript - 在 angularJs 中隐藏 JSON 对象中的重复元素

javascript - 为什么这个函数在处理长数字时比处理短数字时运行得更快?

python - 在 PyMongo 中将 $cond 语句与 $project 和聚合一起使用

javascript - 如何在 Node.js 上使用 JS 库?

javascript - 更改 Node js 上 ChartJS 的背景

javascript - 如何在我当前的 chrome 中使用 puppeteer(保留我的凭据)