猫鼬填充无法正常工作

时间:2018-08-27 12:35:40

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

我在使用mongoose方面非常陌生,并且在mongodb上完成了简单的数据库工作。

看到我的用例,我发现了使用mongoose在mongodb中执行此操作的方法。但是,我并没有获得教程所示的预期结果。

我的模式

var EventsSchema = new mongoose.Schema({
    root: {type: mongoose.Schema.Types.ObjectId, ref: 'root'},
    voting: [{type: mongoose.Schema.Types.ObjectId, ref: 'Voting'}]
});

var VotingSchema = new mongoose.Schema({
    events: {type: mongoose.Schema.Types.ObjectId, ref: 'Events'},
    title: {
        type: String,
        required: true
    }
})

var Events = mongoose.model('Events', EventsSchema, 'event');
var Voting = mongoose.model('Voting', VotingSchema, 'voting');

我最初有这两种模式。我想创建一个投票活动。创建投票事件后,应在voting schema事件中存储id,如所建议的那样,我还想将投票事件引用存储在EventSchema中。

var events = new Events({});
events.save()
.then((events) => {
    var voting = new Voting({ events: events._id, title: "Test Title" });
    voting.save()
    .then((voting) => {
        Voting.findOne({title: 'Test Title'})
        .populate('events')
        .exec(function(err, voting){
            console.log(voting, err);
            if(err) res.sendStatus(401).send();
            else res.sendStatus(200).send();
        })

    })
    .catch((e) => {
        res.sendStatus(401).send();
    });
})
.catch((e) => {
    res.sendStatus(401).send();
})

我在控制台上得到的是

{ 
    _id: 5b83eca82a3cfb1dec21ddc9,
    events: { voting: [], _id: 5b83eca82a3cfb1dec21ddc8, __v: 0 },
    title: 'Test Title',
    __v: 0 
}

我的MongoDB看起来像这样

投票

{
    "_id" : ObjectId("5b83eca82a3cfb1dec21ddc9"),
    "events" : ObjectId("5b83eca82a3cfb1dec21ddc8"),
    "title" : "Test Title",
    "__v" : 0
}

事件

{
    "_id" : ObjectId("5b83eca82a3cfb1dec21ddc8"),
    "voting" : [],
    "__v" : 0
}

我不确定mongodb的外观如何。但是,一旦尝试了代码,它就会像上面一样。

我一定做错了什么或错过了重要的事情。但是文档中也有这种代码。 docs link。帮助我解决此问题。

谢谢

1 个答案:

答案 0 :(得分:0)

ObjId的数组应该在模式中以这种方式定义:

var EventsSchema = new mongoose.Schema({
    root: {type: mongoose.Schema.Types.ObjectId, ref: 'root'},
    voting: {type: [mongoose.Schema.Types.ObjectId], ref: 'Voting'}//**array bracers** 
});

也通过在类型数组字段(如root字段)上调用填充将在API的资源中返回一个空数组,请参阅mongoose.set('debug', true);命中的查询,您会发现猫鼬在事件模型中搜索的不是root。 / p>

尽管您必须在人口方法中告诉猫鼬要使用哪种模型才能使人口正常工作,除非您告诉猫鼬要在哪种模型中进行搜索。

populate({path:'vooting',model:'vooting'})
相关问题