0
votes

i have a array in my mongo database with my users. On register i'm adding a new user ( object ) to this array of users. At the same time i want to create a ObjectID to this new user and create a created_at attribute with the date it was created

let NewUserStructure = {
    _id: ObjectID(),
    username: NewUserUsername,
    nome: NewUserName,
    password: password,
    logado: false,
    especialidades: EspecialidadesArray,
    adm: isadmin,
    cuidade: [],
    $currentDate: {criadoem: true},
    criadopor: createdby,
};
// let query = {_id: '5b193acdfb6fc05a6fe42785'};
let query = {Profissionais: {$exists: true}};
let NewValue = {$addToSet: {Profissionais: NewUserStructure}};
nosqlquery.update('usuarios', query, NewValue, function(result) {
    res.status(200).send(result);
});

I created a generic function for update method on another file

const update = function(targetcollection, query, NewValues, callback) {
console.log('update was called');
_db.collection(targetcollection).updateOne(query, NewValues, function(err, result) {
    if (err) throw err;
    callback(result);
});

};

NewUserStructure is the json i'm inserting on the Profissionais array using $addToSet. I tried to create that unique ObjectID and a new attribute with currentDate from many different ways.

Error : $currentDate is not valid for storage.

I feel that creating a _id field with ObjectID() would not create a unique _id for the user, is there another approach for this also?

1

1 Answers

1
votes

You can't use the $currentDate operator within an $addToSet, so just use new Date() instead, similar to what you're doing with the call to ObjectID() (which is fine):

let NewUserStructure = {
    _id: ObjectID(),
    username: NewUserUsername,
    nome: NewUserName,
    password: password,
    logado: false,
    especialidades: EspecialidadesArray,
    adm: isadmin,
    cuidade: [],
    criadoem: new Date(),
    criadopor: createdby,
};