在猫鼬中使用填充

时间:2020-01-15 15:26:38

标签: javascript mongoose populate

我是猫鼬的新手,我试图让填充对象正常工作,但是返回值始终为null,就好像该引用在集合中将不存在一样,这是错误的:-)

这是我的代码:

mongoose.connect('mongodb://192.168.1.119:27017/DIM').then(() => {
  let p = mongoose.model(
    'Profile',
    new mongoose.Schema({
      _id: mongoose.Schema.Types.ObjectId,
      Name: mongoose.Schema.Types.String,
    }),
    'Profile'
  )

  let m = mongoose.model(
    'User',
    new mongoose.Schema({
      _id: mongoose.Schema.Types.ObjectId,
      Email: mongoose.Schema.Types.String,
      ProfileId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Profile',
      },
    }),
    'User'
  )

  try {
    m.find()
      .populate('ProfileId')
      .select('ProfileId Email _id')
      .exec()
      .then(ret => {
        console.log(JSON.stringify(ret))
      })
  } catch (err) {
    console.log('Error ' + err.message)
  }
})

这是我得到的回报:

[{“ _ id”:“ 5b3ca85a2fcf013a04594f79”,“ Email”:“ sa”,“ ProfileId”:null},{“ _ id”:“ 5b3ca85a2fcf013a04594f7d”,“ Email”:“ remote_log”,“ ProfileId”:null }]

profileId始终为空。

这是数据库的内容

Database

enter image description here

我一定在做些蠢事,但似乎找不到位置。

谢谢!

2 个答案:

答案 0 :(得分:1)

Null的定义是“数据库中不存在的数据值”。您的收藏集中有什么东西要阅读吗?

答案 1 :(得分:0)

好,所以问题在于我连接的数据库是由一个c#应用程序创建的,其中_id不是Mongo ObjectId而是一个字符串GUID,因此我的代码必须适应于:

    let p = mongoose.model(
    'Profile',
    new mongoose.Schema({
      _id: mongoose.Schema.Types.String,
      Name: mongoose.Schema.Types.String,
    }),
    'Profile'
  )

  let m = mongoose.model(
    'User',
    new mongoose.Schema({
      _id: mongoose.Schema.Types.String,
      Email: mongoose.Schema.Types.String,
      ProfileId: {
        type: mongoose.Schema.Types.String,
        ref: 'Profile',
      },
    }),
    'User'
  )