简体   繁体   中英

populate method in mongoose (node js)

I m trying to use populate( ) in node js. Well I m trying to access, objectId of one collection into another collection. for eg., i have collections called Project and events, where i have schema like this.

Project schema:

const projectSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    projectName: {
        type: String,
        required: true,
        unique: true
    },
    dimensions: {
        type: [],
        required: false
    },
    events: {
        [type: mongoose.Schema.Types.ObjectId],
        ref: 'EnrichedEvent'
    },
});
module.exports = mongoose.model('Project', projectSchema);

Events Schema:

const enrichedEventSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    projectId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Project',
        required: true
    },
    name: {
        type: String,
        required: true
    },
    type: {
        type: String,
        enum: ["Enriched"],
        required: true
    },
    source: {
        type: String,
        required: true
    },
});

and the routing code for projects to :

 const express = require("express");
 const router = express.Router();
 const mongoose = require("mongoose");
 const Project = require("../models/project");

 router.get("/", (req, res, next) => {
     Project.find()
         .populate('source', 'EnrichedEvents') //When i use this populate method, I m not able to GET any events on to browser..
         .exec()
         .then(docs => {
             const response = {
                 count: docs.length,
                 projects: docs.map(doc => {
                     return {
                         projectName: doc.projectName,
                         dimensions: doc.dimensions,
                         events: doc.events,
                         _id: doc._id
                     };
                 })
             };
             res.status(200).json(response);
         })
         .catch(err => {
             console.log(err);
             res.status(500).json({
                 error: err
             });
         });
 });

 router.post("/", (req, res, next) => {
     const project = new Project({
         _id: new mongoose.Types.ObjectId(),
         projectName: req.body.projectName,
         events: req.body.events
     });
     project
         .save()
         .then(result => {
             console.log(result);
             res.status(201).json({
                 message: "Created project successfully",
                 createdProject: {
                     projectName: result.projectName,
                     _id: result._id,
                     events: result.events,
                 }
             });
         })
         .catch(err => {
             console.log(err);
             res.status(500).json({
                 error: err
             });
         });
 });

 module.exports = router;

my problem is I can't auto populate the enriched eventsId in projects page. for eg. Whenever i update events they should appear in projects page.but its not happening. In events page also i am not getting corresponding projectId. please point me in right direction.

Populate method takes FIELD_TO_POPULATE and FIELDS_TO_RETURN_FROM_POPULATED_DOC and you are passing it the reversed way. Also in your project schema you have used events for EnrichedEvent , so while populating use events not EnrichedEvent ;

Try the following:

From:

.populate('source', 'EnrichedEvents')

TO:

.populate('events', 'EnrichedEvent')

Edit:

update your schema for EnrichedEvent :

events: [{
 mongoose.Schema.Types.ObjectId, 
 ref: 'EnrichedEvent'
}]

It should work now.

I tried to use a similar .populate('...', '...') method but unsuccessfully. I would use

.populate('source').populate('EnrichedEvent')

or ('EnrichedEvents') depending on what you have defined in your schema.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM