Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose object id is null

I'm creating an object Registration (a Mongoose Schema) and I need to set its Id in User with this line: registrationId: registration._id});

However, the Id is still null, even though it's the callback function? When I check the database the Registration has and Id of course, but not in the callback. How can I set the Id of the Registration in User?

Edit2: changed to minimal example. This prints out two times null.

exports.create = function(req, res) {
  Registration.create(req.body, function(err, registration) {
    if(err) { return handleError(res, err); }

    console.log(registration._id);
    console.log(registration.id);

    return res.json(201, registration);
  });
};

Edit: this is the schema (I left out some fields that are not required):

'use strict';

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var RegistrationSchema = new Schema({

    isReservation: Boolean,

    //Id of the trip
    tripId: String,

    //socialMutuality
    codeGerechtige: String,
    socialMutualityNumberParent1: String,
    socialMutualityNumberParent2: String,

    //contact
    userId: String,
    firstnameContact: String,
    lastnameContact: String,
    emailContact: String,
    streetContact: String,
    streetNumberContact: String,
    zipcodeContact: String,
    busContact: String,
    cityContact: String,
    phoneContact: String,
    gsmContact: String,
    socialSecurityNumberContact: String,

    //coordinats of person that pays

    //child information

    //emergency contacts
    emergencyContacts: [{
        firstName: String,
        lastName: String,
        phone: String
    }],

    extraInfo: String

});

module.exports = mongoose.model('Registration', RegistrationSchema);

Problem and solution: the problem was the client sending an attribute _id = null, and that's why MongoDB/Mongoose didn't update the id.

like image 758
Aaron Avatar asked Dec 15 '14 17:12

Aaron


People also ask

What is object ID in Mongoose?

An ObjectID is a 12-byte Field Of BSON type. The first 4 bytes representing the Unix Timestamp of the document. The next 3 bytes are the machine Id on which the MongoDB server is running.

Does Mongoose create ID automatically?

By default, Mongoose adds an _id property to your schemas. const schema = new Schema(); schema. path('_id'); // ObjectId { ... } When you create a new document with the automatically added _id property, Mongoose creates a new _id of type ObjectId to your document.

What is the type of ID in Mongoose?

Many other databases use a numeric id property by default, but in MongoDB and Mongoose, ids are objects by default.

Is Mongoose ID unique?

It does. One part of id is a random hash and another is a unique counter common accross collections.


2 Answers

removing _id from req.body fixed my issue.

if(req.body._id === null) {
  delete req.body._id;
}
like image 200
zeah Avatar answered Nov 03 '22 10:11

zeah


There must be something else going on in your code which is effecting this. This example works as expected for me:

'use strict';

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/createid');

var RegistrationSchema = new Schema({

    isReservation: Boolean,

    //Id of the trip
    tripId: String,

    //socialMutuality
    codeGerechtige: String,
    socialMutualityNumberParent1: String,
    socialMutualityNumberParent2: String,

    //contact
    userId: String,
    firstnameContact: String,
    lastnameContact: String,
    emailContact: String,
    streetContact: String,
    streetNumberContact: String,
    zipcodeContact: String,
    busContact: String,
    cityContact: String,
    phoneContact: String,
    gsmContact: String,
    socialSecurityNumberContact: String,

    //coordinats of person that pays

    //child information

    //emergency contacts
    emergencyContacts: [{
        firstName: String,
        lastName: String,
        phone: String
    }],

    extraInfo: String

});

var Registration = mongoose.model('Registration', RegistrationSchema);

var reg = {
    userId: '1234',
    tripId: '2345',
    firstnameContact: 'Timothy',
    lastnameContact: 'Strimple',
    emailContact: '[email protected]'
};

Registration.create(reg, function(err, registration) {
    if(err) { throw err; }
    console.log(registration._id);
});

I get a valid id written out to the console.

like image 42
Timothy Strimple Avatar answered Nov 03 '22 08:11

Timothy Strimple