I have the below Mongoose function where I am trying to do a select WHERE email = req.body.email and referenceId is not in an array.
referenceId is a string array [String] which has an array of object ID's.
const refereeSchema = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
referenceId: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
}
],
token: {
type: String,
required: true
},
password: {
type: String
},
company: {
type: String,
required: true
},
role: {
type: String,
required: false
},
startedOn: Date,
endedOn: Date,
createdAt: Date,
updatedAt: Date
});
Referee.findOneAndUpdate({
email: req.body.email,
referenceId: {
'$ne': [new mongo.ObjectID(req.params.referenceId)]
}
}, {
$push: {
referenceId: new mongo.ObjectID(req.body.referenceId)
}
}, {
new: true
}, (err, doc) => {
if (err) {
res.status(401).send(err);
}
res.send(doc);
});
Each time I run the above it always matches and pushes the ObjectId even though it already existed before.
{ referenceId:
[ 5ba94232b492890982e7a417,
5ba94232b492890982e7a417,
5c20d8f907a55accd720c27f,
5c20d8f907a55accd720c27f,
5c20d8f907a55accd720c27f,
5c20d8f907a55accd720c27f,
5c20d8f907a55accd720c27f,
5c20d8f907a55accd720c27f ],
_id: 5c20e86d72d5c1ce20b961fa,
firstName: 'Richard',
lastName: 'Hendricks',
email: 'hello@domain.com',
token: '319d9f5a-68e1-6f47-a9f1-7fbbf617a45c',
company: 'Pied Piper',
role: '',
__v: 0 }
Could someone please help me?
I'd like to do a check to see if the ObjectId is already in the array then DO NOTHING else push it.