3

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")
}
2
  • Just a guess, but something like findOne{ username: req.user.username, "userFollows.user": { $ne: req.body.userID } }) should work. The important difference is calling findOne with one object, not two. Commented Feb 21, 2014 at 12:51
  • I'm getting this error: {"code":"InternalError","message":"Cannot read property 'userFollows' of null"} with both my query and the one above Commented Feb 21, 2014 at 13:15

2 Answers 2

1
+50

There are two ways that you can do this update (in shell syntax):

db.users.update( 
     { "username": req.user.username },
     { $addToSet : { userFollows : { _id: ObjectId("53073acd9256e81e4d7b5d8e"),
                                     status: "followed_by",
                                     added: ISODate("2014-02-21T11:38:53.828Z"),
                                     user: ObjectId("51c6ec9fedc1230700000007")
                                   }
                   }
     }
)

which says, for this user, add to userFollows array this object (unless it's already there).

The other way to do it is:

db.users.update( 
     { "username": req.user.username, "userFollows.user": { $ne: req.body.userID } },
     { $push : { userFollows : { _id: ObjectId("53073acd9256e81e4d7b5d8e"),
                                     status: "followed_by",
                                     added: ISODate("2014-02-21T11:38:53.828Z"),
                                     user: ObjectId("51c6ec9fedc1230700000007")
                                   }
                   }
     }
)

which says: for this user, who doesn't already have this follower, $push this object.

Obviously you would fill in appropriate fields - I simply cut-n-paste some sample values from your question to show the full format.

Sign up to request clarification or add additional context in comments.

Comments

0

Checkout this about adding data to nested array within an update query.

db.collection.update( 
    { username: req.user.username }, 
    { $addToSet: { "userFollows.user": req.user.usernameThatIAdd } }
 );

4 Comments

Will this work if I need to add the status and added fields as well ? The final userFollows object looks like this: { status: "followed_by", added: ISODate("2014-02-21T11:38:53.828Z"), user: ObjectId("51c6ec9fedc1230700000007"), _id: ObjectId("53073acd9256e81e4d7b5d8e") }
userFollows is more than just a user name though. So, $addToSet as you've suggested won't work.
And, you'll find it won't actually work syntactically. You'll get an error can't append to array using string field name: user. You can't use the dot syntax with $addToSet.
Doubling @WiredPrairie this just will not work. And for the second time recently I ask. "Who is up-voting these completely untested and wrong answers?"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.