Search code examples
node.jsmongodbexpressmongoosemongoose-schema

How to access each field value in mongodb data queried using mongoose with mixed type schema


I have data in database like below. Model is defined like const Any = new Schema({ any: {} });. Now if i query const user = await Any.find({}); and try to console.log(user.name, user.email) it gives undefined. If I modify model then it is working perfectly , but I want it to be mixed type. Is there any way to do so, or I have to modify schema. I'm using mongoose to connect to database.

{
  _id: "213337867hgduhg3",
  name: "some name",
  email: "someone@email.com",
}

Solution

  • To access each properties of the first you have to use toObject method.

    Taking your case, code will be like this.

    const mongoose = require('mongoose');
    const Any = new mongoose.Schema({});
    const AnySchema = mongoose.model("collection', Any);
    
    async function someFunction(){
      const user = await AnySchema.findOne({email: 'someone@gmail.com'}); 
        //or find() for multiple result , 
        //iterate through them to get individual document
      if(user){
         console.log(user);
         console.log('name:' + user.name);
         console.log('name: ' + user.toObject().name);
      }
    }
    

    Outut will be like :

    {
      _id: "213337867hgduhg3",
      name: "some name",
      email: "someone@email.com",
      _v: 0
    }
    
    name: undefined
    name: some name
    

    first user.name is undefined. To access each property use javaScript toObject method to convert it to javaScript object.