Say I have a User schema:
UserSchema = new Schema({
name: {
first: { type: String, trim: true },
last: { type: String, trim: true }
},
username: { type: String, trim: true, required: true },
email: { type: String, trim: true, required: true },
hashed_password: { type: String, trim: true, required: true },
profile_image: { type: String, trim: true, default: 'default' },
join_date: { type: Date, required:true },
userFollows: [ {
status : { type: String, enum: [
'following',
'followed_by'
]},
added : { type: Date, required:true },
user : { type: Schema.ObjectId, ref: 'User'}
} ]
})
I need to push a new userFollows in to this schema but I also need to check the user does not currently follow the user (duplicate entry) but am not sure how to perform this query
The current query I am attempting to use is:
User
.findOne(
{ username: req.user.username },
{ "userFollows.user": { $not: req.body.userID } }
)
.exec(function (err, currentUser) {
})
But it's not working.
I'd like to avoid looping through the currentUser.userFollows array after the query is performed and manually checking
Final userFollows object I need to push looks like this:
{
_id: ObjectId("53073acd9256e81e4d7b5d8e"),
status: "followed_by",
added: ISODate("2014-02-21T11:38:53.828Z"),
user: ObjectId("51c6ec9fedc1230700000007")
}
findOne{ username: req.user.username, "userFollows.user": { $ne: req.body.userID } })should work. The important difference is calling findOne with one object, not two.