2

I want to access the content of array of document in my model, but I can't and return undefined.
here is my model(Project.js):

var mongoose = require('moongoose');
var Schema = mongoose.Schema;
var User = require("./Users");

var ProjectSchema = new Schema({
   name: String,
   description: String,
   owner: {
   type: mongoose.SchemaTypes.ObjectId,
      ref: "User"
   },
   contributor: [{
      type: mongoose.SchemaTypes.ObjectId,
      ref: "User"
   }]
});

module.exports = mongoose.model('Project', ProjectSchema);

and my Api:

var Project = require('./Project')

await Project.find({owner: userId, name: name})
.then(project => {

   console.log(project);
   console.log(project.contributor);
}).catch(err => {
   res.status(500).send({
   message: err.message
   });
});

when i try console.log(project); return expected output but in console.log(project.contributor); return undefined

I've also searched the web but couldn't find anything right and clear solution

I appreciate any help :)

hamid
  • 93
  • 1
  • 6
  • Please show output of console.log(project) – AConsumer Jan 21 '19 at 08:58
  • project.contributor is an array with one object, so you need to determent witch one you want even though there is only one object in the array, so try console.log(project.contributor[0]) – Flubssen Jan 21 '19 at 09:00
  • Possible duplicate of [Access / process (nested) objects, arrays or JSON](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – str Jan 21 '19 at 09:06
  • 1
    `project` is an array, not an object. Thus you have to use `project[0].contributor`. – str Jan 21 '19 at 09:07

2 Answers2

2

As you are expecting to find only one project, change find by findOne method. Other case you are searching for several projects and you are going to receive an array instead of an object.

David Vicente
  • 3,091
  • 1
  • 17
  • 27
1

Your output from Project.find() (See) will be an array of objects from the database.

If you will only have 1 object as a result then you can use project[0].contributor because project is an array with 1 object inside it, which is on the index 0.

If the result might have many objects in the array then you should iterate through the result to get each of the data individually.

project.forEach(p => console.log(p.contributor))
holydragon
  • 6,158
  • 6
  • 39
  • 62