【问题标题】:populate method in mongoose (node js)猫鼬中的填充方法(节点js)
【发布时间】:2018-10-14 13:50:58
【问题描述】:

我正在尝试在节点 js 中使用 populate()。 好吧,我正在尝试将一个集合的 objectId 访问到另一个集合中。 例如,我有名为 Project 和 events 的集合, 我有这样的架构。

项目架构:

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);

事件架构:

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
    },
});

以及项目的路由代码:

 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;

我的问题是我无法在项目页面中自动填充丰富的eventsId。 例如。每当我更新事件时,它们应该出现在项目页面中。但它没有发生。在事件页面中,我也没有得到相应的 projectId。请指出正确的方向。

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongoose-populate


    【解决方案1】:

    Populate 方法采用 FIELD_TO_POPULATEFIELDS_TO_RETURN_FROM_POPULATED_DOC 并且您以相反的方式传递它。同样在您的项目架构中,您将events 用于EnrichedEvent,因此在填充时使用events 而不是EnrichedEvent

    尝试以下方法:

    发件人:

    .populate('source', 'EnrichedEvents')

    到:

    .populate('events', 'EnrichedEvent')

    编辑:

    更新EnrichedEvent 的架构:

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

    它现在应该可以工作了。

    【讨论】:

    • 抱歉,您在项目架构中已将EnrichedEvents 定义为events。我已更新我的答案请立即尝试,看看它是否有效。
    • 给出错误:{"error":{"message":"Cast to ObjectId failed for value \"123456\" at path \"_id\" for model \"EnrichedEvent\""," name":"CastError","stringValue":"\"123456\"","kind":"ObjectId","value":"123456","path":"_id"}}
    • 123456 似乎不是 mongodb ObjectId。这就是我猜它给出错误的原因。你能检查一下你是否收到了正确的 mongodb ObjectId 事件。
    • 我需要将数据发布到丰富的事件模式中,然后我必须将 eventid 更新到项目中,然后它的工作。但我需要项目模式来自动更新相对于相应 projectId 的 eventid。
    • @darshanan 你能分享一下你在console.log(result);的帖子路线中得到了什么
    【解决方案2】:

    我尝试使用类似的.populate('...', '...') 方法但没有成功。我会用

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

    ('EnrichedEvents'),具体取决于您在架构中定义的内容。

    【讨论】:

      猜你喜欢
      • 2015-11-19
      • 2015-06-20
      • 2020-06-25
      • 1970-01-01
      • 2015-05-29
      • 2015-07-13
      • 2016-10-10
      • 2017-12-11
      相关资源
      最近更新 更多