将字符串从一个集合引用到另一个集合(mongoose schema)

时间:2018-05-11 10:50:22

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

我需要知道如何将String从一个集合引用到另一个集合? 我有一个这样的模型。

const enrichedEventSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
projectId: { type: mongoose.Schema.Types.ObjectId, ref: 'Project', required: true },
name: { type: String, required: true },
address: { type: String, required: true }
});

现在我的需求已经改变,而不是projectId我需要引用projectName 这是一个字符串,在过去的5个小时里,我尝试了所有这些可能的方法,它无法正常工作,有人引导我朝正确的方向发展。

const enrichedEventSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
projectName: { type: String, ref: 'Project', required: true },
name: { type: String, required: true },
address: { type: String, required: true }
    });

我也尝试了这一行,

projectName: { type: mongoose.Schema.Types.String, ref: 'Project', required: true }

我正在尝试这个查询:

router.post("/", (req, res, next) => {
Project.findOneAndUpdate({projectName:projectName}, 
       { $push: { enrichedEvents: enrichedEventId}},
            function (error, success) {
                if (error) {
                    console.log(error);
                } else {
                    console.log(success);
                }
            });

const enrichedEvent = new EnrichedEvent({
    _id: mongoose.Types.ObjectId(),
    name: req.body.name,
    projectName: req.body.projectName, 
});
return enrichedEvent.save()
    .then(result => {
        console.log(result);
        res.status(201).json({
            message: "Event stored",
            createdEvent: {
                _id: result._id,
                project: result.project,
                name: result.name,

            },
        });
    })
    .catch(err => {
        console.log(err);
        res.status(500).json({
            error: err
        });
    });
});

0 个答案:

没有答案