Home > Enterprise >  Mongoose returns a null from a value with schematype Object Id
Mongoose returns a null from a value with schematype Object Id

Time:01-04

Simple mongoose Schema with a value 'base_id' with type Object.id

const mongoose = require ('mongoose');

const Schema = mongoose.Schema;

const qrSchema = new Schema({
    token: {
        type: String,
        unique: true,
        required: true
    },
    base_id : {        
        type: mongoose.Schema.Types.ObjectId, ref: 'Base'
    },    
    // etc
});

const QR = mongoose.model('QR', qrSchema);
module.exports = QR;

The ref 'Base' refers to another model. I would like to extract a populated result. But even an ordinary request without population:

const user = await QRToken.findOne({token: req.query.token})    

console.log(user)

returns a null for 'base_id' in the console.log in response:

{
  _id: new ObjectId("631230020d0572fac188dc1"),      
  token: '9bb8329611qab805f4bcc7f3066c94cbbd0d430f8fcf4cea09bdf191ef89887',
  base_id: null,
   //etc      
}

//base Schema
const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const baseSchema = new Schema({
    firstname: {
        type: String,
        required: true
    },
    lastname: {
        type: String,
        required: true
    },
    userName: { //mailaddress
        type: String,
        unique: true,
        trim: true,
        lowercase: true
    },
    telephone: {
        type: String,
        unique: true,
        trim: true
    },
    password: {
        type: String,
        required: true,
        select: false
    },

    token: {
        type: String
    }
}, options);


const Base = mongoose.model('Base', baseSchema);
module.exports = Base;

What am I doing wrong?

CodePudding user response:

remarkable why I had this error. lpizzinidev triggered me to check the Base model. I use this model, populating etc, now 2 years in a pilot. Never an error. Maybe with updating things changed it is case-sensitive.

const mongoose = require('mongoose');

const Schema = mongoose.Schema;


//discriminatorKey
const options = {
    discriminatorKey: 'kind',
    collection: 'base'
};

//change the collectionname from 'Base' to 'base' did the job.

  • Related