0

I want to use findOne() on Mongoose to find ObjectId in Twitter JSON credentials from Twitter account.

I am using following schema and code:

var userSchema = new Schema({
    provider: String,
    name: String,
    email: String,
    username: String,
    twitter: JSON
});

User.findOne({
    'twitter.id_str': 123
}, function (err, user) {
    if (err) {
        return done(err);
    }
    if (!user) {
        user = new User({
            name: 'Full Name',
            email: 'mail@gmail.com',
            username: 'pseudo',
            provider: 'twitter',
            twitter: { id_str: 123 }
        });
        user.save(function (err) {
            if (err) console.log(err);
            console.log(user);
        });
    } else {
        console.log(user);
    }
});
greuze
  • 4,250
  • 5
  • 43
  • 62
  • Is the Twitter `id_str` a Mongo/Mongoose Object ID or is that a Twitter user id? Either way if you're going to be searching on a field you will save yourself some headache to model it more specifically in your Schema. Instead of `JSON` use the data type of each field in the object. – ballenf Feb 20 '17 at 23:07
  • It's the Twitter ID profile. I stock this in twitter key. –  Feb 21 '17 at 09:53

1 Answers1

0

Change your schema to either:

var userSchema = new Schema({
    provider: String,
    name: String,
    email: String,
    username: String,
    twitterId: { type: Number, unique: true }
});

or

var userSchema = new Schema({
    provider: String,
    name: String,
    email: String,
    username: String,
    twitter: { id: { type: Number, unique: true } }
});

The second is more like your current setup. If you use that schema, your search code could be a findOne with the optional upsert flag on findOneAndUpdate():

User.findOneAndUpdate({
    'twitter.id_str': 123
}, {
    name: 'Full Name',
    email: 'mail@gmail.com',
    username: 'pseudo',
    provider: 'twitter',
    twitter: { id_str: 123 }
}, {
    upsert: true
}, function (err, user) {
    if (err) {
        return done(err);
    } else {
        console.log(user);
    }
});

See here for another example of usage: How do I update/upsert a document in Mongoose?

Community
  • 1
  • 1
ballenf
  • 894
  • 10
  • 19