Reputation: 172
I don't know if this a mongoose bug or I'm doing something wrong, my problem is:
I have some documents in the mongoDB these have an attribute called address and inside it have an country which is an object id but when I make a query using mongoose this country id comes as "null":
Mongoose Schema
{
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 document:
{
"_id" : ObjectId("54b7ff802d244c9f224c78f4"),
"password" : "12345",
"email" : "[email protected]",
// ...
"address" : {
"country" : ObjectId("54e635cb4ef1d41d99b837e8"),
"zipCode" : "",
"city" : "",
"address" : ""
}
}
Mongoose query
Model.findOne({
email: '[email protected]',
password: '12345'
}, function(err, model) { /* ... */ });
Mongoose response
{
"_id": "54b7ff802d244c9f224c78f4",
"email": "[email protected]",
"password" : "12345",
// ...
"address": {
"country": null,
"zipCode": "",
"city": "",
"address": ""
}
}
I really don't know why country is coming as null. My Mongo version is 2.6.6 and mongoose version is 3.8.21.
Any ideas?
Upvotes: 1
Views: 613
Reputation: 172
I've solved it, I'll describe how did I fix it:
Update mongoose to 3.8.23 (I don't think it made any difference).
When I was running the init script, the script imports a csv doc with countries data, so the country _id changes on each mongoimport; so I made a mongodump and now in init script I restore the collection instead importing it.
I think this last point made the difference because of the _id; in the schema I'm setting an default ObjectId that does not exists in the collection, thats why i decided to make an restore, to hold all _id's.
Upvotes: 0
Reputation: 12290
This can be fixed using populate
Model.findOne({
email: '[email protected]',
password: '12345'
}).populate('address country').exec(function (error, user) {
// ...
});
Upvotes: 1