abrahamebij
abrahamebij

Reputation: 153

How to store a mongoose result into a variable

I am unable to store my mongoose.js results(it's an object). Below is my code.

mongoose.connect('mongodb://localhost:27017/templatesDB', {useNewUrlParser: true});
const templateSchema = new mongoose.Schema({
    _id: Number,
  title: String,
    aside: Array,
  downloads: Number,
  type: String,
    meta: {
        title: String,
        desc: String,
        imgURL: String,
        imgAlt: String,
        URL: String,
        keywords: Array
    },
    template: {
        name: String,
        img: String,
        imgAlt: String,
    },
    developer: {
        name: String,
        href: String,
    },
    links: {
        download: String,
        preview: String,
        github: String,
    },
    technologies: Array,
    tags: Array,
    about: {
        desc: String,
        usage: Array
    }
});

let json = {
        _id: 1,
        title: "Mansionify",
        downloads: 0,
        type: "landing",
        meta: {
            title: "Mansionify Landing Page",
            desc: "Real Estate Landing Page By Abraham Ebijuni",
            imgURL: "/img/png/mansionify.png",
            imgAlt: "Mansionify Preview Image",
            URL: "/templates/mansionify",
            keywords: ["Mansionify", "Landing Page", "Real", "Estate", "Real Estate", "Page", "Housing", "Big House", "Mansion", "Mansions", "html", "html5", "css", "tailwindcss", "tailwind", "npm", "Abraham", "Ebijuni", "Abraham Ebijuni"]
        },
        template: {
            name: "Mansionify",
            img: "/img/png/mansionify.png",
            imgAlt: "Mansionify Preview Image",
        },
        developer: {
            name: "Abraham Ebijuni",
            href: "https://github.com/abrahamebij",
        },
        links: {
            download: "/templates/manionify/download",
            preview: "https://github.com/abrahamebij/bootstrap-bootcamp",
            github: "https://github.com/abrahamebij/my-calculator",
        },
        technologies: ["html", "tailwindcss", "npm"],
        tags: ["Landing Page", "Real Estate", "Housing"],
        about: {
            desc: "Mansionify is a basic Tailwind 3.0 Real Estate landing page that you can download and use out of the box without having to change any file paths. Everything you need to start development on this Tailwind project is here, which includes the core Tailwind CSS and JS bundle along with OwlCalrousel Library.",
            usage: ["cd 'Project\ Folder'", "npm install", "npx tailwindcss --watch", "And you are good to go"]
        },
        aside: [
            {
                img: "/img/png/templatify.png",
                imgAlt: "Templatify Overview",
                title: "Templatify",
                desc: "A landing page for templates",
                downloads: 2,
                link: "/donate",
            },
            {
                img: "/img/png/w3schools.png",
                imgAlt: "W3shools Overview",
                title: "W3schools",
                desc: "A website page for web learning",
                downloads: 2,
                link: "/contact",
            },
            {
                img: "/img/png/mansionify.png",
                imgAlt: "Mansionify Overview",
                title: "Mansionify",
                desc: "A landing page for real estate",
                downloads: 2,
                link: "/mansionify",
            },
        ]
    };

Saving the object

const Template = mongoose.model("Template", templateSchema);

const template = new Template(json)
template.save();

Now when I try to access it using the console.log() method, it works

Template.findOne(function (err, temp) {
  console.log(err ? err : temp); // returns the object
});

If I try to store it into a variable

const data = Template.find(function (err, temp) {
  return (err ? err : temp);
});

console.log(data)

It just returns this whole stuff

Query {
  _mongooseOptions: {},
  _transforms: [],
  _hooks: Kareem { _pres: Map(0) {}, _posts: Map(0) {} },
  _executionStack: null,
  mongooseCollection: Collection {
    collection: null,
    Promise: [Function: Promise],
    modelName: 'Template',
    _closed: false,
    opts: {
      autoIndex: true,
      autoCreate: true,
      schemaUserProvidedOptions: {},
      capped: false,
      Promise: [Function: Promise],
      '$wasForceClosed': undefined
    },
    name: 'templates',
    collectionName: 'templates',
    conn: NativeConnection {
      base: [Mongoose],
      collections: [Object],
      models: [Object],
      config: {},
      replica: false,
      options: null,
      otherDbs: [],
      relatedDbs: {},
      states: [Object: null prototype],
      _readyState: 2,
      _closeCalled: false,
      _hasOpened: false,
      plugins: [],
      id: 0,
      _queue: [],
      _listening: false,
      _connectionString: 'mongodb://localhost:27017/templatesDB',
      _connectionOptions: [Object],
      client: [MongoClient],
      '$initialConnection': [Promise]
    },
    queue: [],
    buffer: true,
    emitter: EventEmitter {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      [Symbol(kCapture)]: false
    }
  },
  model: Model { Template },
  schema: Schema {
    obj: {
      _id: [Function: Number],
      title: [Function: String],
      aside: [Function: Array],
      downloads: [Function: Number],
      type: [Function: String],
      meta: [Object],
      template: [Object],
      developer: [Object],
      links: [Object],
      technologies: [Function: Array],
      tags: [Function: Array],
      about: [Object]
    },
    paths: {
      _id: [SchemaNumber],
      title: [SchemaString],
      aside: [SchemaArray],
      downloads: [SchemaNumber],
      type: [SchemaString],
      'meta.title': [SchemaString],
      'meta.desc': [SchemaString],
      'meta.imgURL': [SchemaString],
      'meta.imgAlt': [SchemaString],
      'meta.URL': [SchemaString],
      'meta.keywords': [SchemaArray],
      'template.name': [SchemaString],
      'template.img': [SchemaString],
      'template.imgAlt': [SchemaString],
      'developer.name': [SchemaString],
      'developer.href': [SchemaString],
      'links.download': [SchemaString],
      'links.preview': [SchemaString],
      'links.github': [SchemaString],
      technologies: [SchemaArray],
      tags: [SchemaArray],
      'about.desc': [SchemaString],
      'about.usage': [SchemaArray],
      __v: [SchemaNumber]
    },
    aliases: {},
    subpaths: {
      'aside.$': [Mixed],
      'meta.keywords.$': [Mixed],
      'technologies.$': [Mixed],
      'tags.$': [Mixed],
      'about.usage.$': [Mixed]
    },
    virtuals: { id: [VirtualType] },
    singleNestedPaths: {},
    nested: {
      meta: true,
      template: true,
      developer: true,
      links: true,
      about: true
    },
    inherits: {},
    callQueue: [],
    _indexes: [],
    methods: {},
    methodOptions: {},
    statics: {},
    tree: {
      _id: [Function: Number],
      title: [Function: String],
      aside: [Function: Array],
      downloads: [Function: Number],
      type: [Function: String],
      meta: [Object],
      template: [Object],
      developer: [Object],
      links: [Object],
      technologies: [Function: Array],
      tags: [Function: Array],
      about: [Object],
      __v: [Function: Number],
      id: [VirtualType]
    },
    query: {},
    childSchemas: [],
    plugins: [ [Object], [Object], [Object], [Object], [Object] ],
    '$id': 1,
    mapPaths: [],
    s: { hooks: [Kareem] },
    _userProvidedOptions: {},
    options: {
      typeKey: 'type',
      id: true,
      _id: true,
      validateBeforeSave: true,
      read: null,
      shardKey: null,
      discriminatorKey: '__t',
      autoIndex: null,
      minimize: true,
      optimisticConcurrency: false,
      versionKey: '__v',
      capped: false,
      bufferCommands: true,
      strictQuery: true,
      strict: true,
      pluralization: true
    },
    '$globalPluginsApplied': true,
    _requiredpaths: [],
    _indexedpaths: []
  },
  op: 'find',
  options: {},
  _conditions: {},
  _fields: undefined,
  _update: undefined,
  _path: undefined,
  _distinct: undefined,
  _collection: NodeCollection {
    collection: Collection {
      collection: null,
      Promise: [Function: Promise],
      modelName: 'Template',
      _closed: false,
      opts: [Object],
      name: 'templates',
      collectionName: 'templates',
      conn: [NativeConnection],
      queue: [],
      buffer: true,
      emitter: [EventEmitter]
    },
    collectionName: 'templates'
  },
  _traceFunction: undefined,
  '$useProjection': true
}

How can I save that particular object into a variable? Thanks for reading.

Upvotes: 1

Views: 1699

Answers (1)

Nisan Coşkun
Nisan Coşkun

Reputation: 561

If you want to store the result of query in a variable that outside of your callback function you have to await the query:

let data;
try {
  data = await Template.find();
} catch(err) {
  console.log(err);
}

console.log(data);

Make sure you have async keyword in front of the function you write the query.

Upvotes: 2

Related Questions