Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't access object property of a Mongoose response

I'm running this code on node.js

var mongoose = require('mongoose');
mongoose.model('participant',new mongoose.Schema({},{ collection : 'forumParticipant' }));
var Participant = mongoose.model('participant');
mongoose.connect('******');

Participant.find({entity_id: 0}, function (err, docs) {
   console.log(docs[0]);
   console.log(docs[0].entity_id)
});

1) The first console.log return the full document

2) The second console.log return undefinied

I don't understand why.

I need to perform something like

var participants = docs.map(function(d){return d.user_id})

How can I achieve that? What am I missing ?

like image 362
Hugo Avatar asked Sep 17 '15 14:09

Hugo


People also ask

Why is object property undefined JavaScript?

The JavaScript warning "reference to undefined property" occurs when a script attempted to access an object property which doesn't exist.

Can I use $in in mongoose?

For example, if we want every document where the value of the name field is more than one value, then what? For such cases, mongoose provides the $in operator. In this article, we will discuss how to use $in operator. We will use the $in method on the kennel collection.

What is mongoose model ()?

A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.

What problem does mongoose JS solve?

Mongoose is a Node. js-based Object Data Modeling (ODM) library for MongoDB. It is akin to an Object Relational Mapper (ORM) such as SQLAlchemy for traditional SQL databases. The problem that Mongoose aims to solve is allowing developers to enforce a specific schema at the application layer.


1 Answers

I suspect the value you are trying to get is not in your Schema but is stored in your database.

You have two solutions from there. You can either add entity_id to your Schema and Mongo will be able to bind it to the Document object you receive. This is the recommended way.

Or you can bypass mongoose Schema and access the raw document stored in the database with docs[0]._doc.entity_id. I don't recommend this solution unless you know what you're doing.

like image 185
Masadow Avatar answered Sep 22 '22 22:09

Masadow