Reputation: 45
First of all my code is obviously simplified. I create a new field named "followers", in order to store followers names, as array type.
USER SCHEMA
var userSchema = new mongoose.Schema({
local:{
localId:{type:Number},
username:{type:String},
email:{type:String},
followers:{type:Array}
},
facebook:{
facebookId: {type:Number},
username:{type:String},
email:{type:String},
followers:{type:Array}
},
twitter:{
twitterId: {type:Number},
username:{type:String},
email:{type:String},
followers:{type:Array}
}
});
{ "_id" : ObjectId("...."), "facebook" : { "facebookId" : 10215321125408144, "username" : "johnny", "email" : "[email protected]}, "__v" : 0 }
But something weird comes up. When i make a query:
User.findOne({$or: [
{'local.username': 'johnny' },
{ 'facebook.username': 'johnny' },
{ 'twitter.username': 'johnny' },
]}, function(err, user) {
if(err){console.log(err);}
if(!user){
console.log('cannot find user');
}
if(user){
console.log('usrInfo is : '+user);
return res.send(JSON.stringify(user));
}
});
i get as a result:
usrInfo is : { _id: 5a60de744b85e14051e03e2e,
__v: 0,
twitter: { followers: [] },
facebook:
{ facebookId: .....,
username: 'johnny',
email: '[email protected]',
.............,
followers: [] },
local: { followers: [] } }
I cannot understand why
twitter: { followers: [] } and local: { followers: [] }
are showing up. Is there any way to avoid this; Because i'm new in MongoDB i would appreciate any explanation why MongoDB does that. Thanks
Upvotes: 0
Views: 552
Reputation: 7220
This issue occurs because, according to the Mongoose documentation, fields in your schema with type Array
implicitly have a default value of []
. Try setting the default value to undefined
and see if that resolves your problem:
var userSchema = new mongoose.Schema({
local:{
localId:{type:Number},
username:{type:String},
email:{type:String},
followers:{type:Array, default: undefined}
},
facebook:{
facebookId: {type:Number},
username:{type:String},
email:{type:String},
followers:{type:Array, default: undefined}
},
twitter:{
twitterId: {type:Number},
username:{type:String},
email:{type:String},
followers:{type:Array, default: undefined}
}
});
Upvotes: 1