为什么Mongoose在DB中存在响应空字段(已解决)

我不知道这是一个mongoose错误还是我做错了,我的问题是:

我在mongoDB中有一些文件,这些文件有一个叫做地址的属性,里面有一个国家,它是一个对象ID,但是当我用mongoose做查询时,这个国家ID是“null”:

mongoose纲要

{ password: { type: String, trim: true, required: true, index: true }, email: { type: String, trim: true, required: true, index: { unique: true } }, address: { address: { type: String, default: '' }, city: { type: String, default: '' }, zipCode: { type: String, default: '' }, country: { type: Schema.ObjectId, ref: 'Country', default: '54e635cb4ef1d41d99b837e8', required: true } } 

}

MongoDB文档:

 { "_id" : ObjectId("54b7ff802d244c9f224c78f4"), "password" : "12345", "email" : "email@email.com", // ... "address" : { "country" : ObjectId("54e635cb4ef1d41d99b837e8"), "zipCode" : "", "city" : "", "address" : "" } } 

mongoose查询

 Model.findOne({ email: 'email@email.com', password: '12345' }, function(err, model) { /* ... */ }); 

mongoose响应

 { "_id": "54b7ff802d244c9f224c78f4", "email": "email@email.com", "password" : "12345", // ... "address": { "country": null, "zipCode": "", "city": "", "address": "" } 

}

我真的不知道为什么国家会变成空白。 我的Mongo版本是2.6.6,mongoose版本是3.8.21。

有任何想法吗?

这可以使用填充来解决

 Model.findOne({ email: 'email@email.com', password: '12345' }).populate('address country').exec(function (error, user) { // ... }); 

我已经解决了,我会介绍一下如何解决这个问题:

  1. 更新mongoose3.8.23(我不认为这有什么区别)。

  2. 当我运行初始化脚本时,脚本导入一个带有国家数据的csv文档,所以国家_id在每个mongoimport上都会改变; 所以我做了一个mongodump,现在在init脚本中恢复集合,而不是导入它。

我认为这最后一点是因为_id; 在架构中,我设置了一个默认的ObjectId,它不存在于集合中,这就是为什么我决定进行还原,以保存所有的_id。