首页 > 解决方案 > Mongoose populate not working as expected

问题描述

I am very much new in using mongoose and had done simple db work on mongodb.

Seeing my usecase I found this method of doing it in mongodb using mongoose. However I am not getting expected result as shown in tutorials.

My Schemas

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

I have these two schemas initially. I want to create a voting event. When voting event is created then in voting schema events id should be stored as suggested and more I want is that voting event reference should be stored in 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();
})

What I am getting on console is

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

My MongoDB looks like this

voting

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

events

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

I am not sure how will my mongodb look like. But after attempting the code once it looks like above.

I must be doing something wrong or missing something important. But this kind of code is there in docs too. docs link. Help me in sorting this issue.

Thanks

标签: node.jsmongodbmongoosemongoose-schemamongoose-populate

解决方案


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

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

同样在数组类型的字段(如 root 字段)上调用 population 将在 API 的 res 中返回一个空数组,查看mongoose.set('debug', true);您命中的查询会注意到 mongoose 在事件模型中搜索而不是 root。

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

populate({path:'vooting',model:'vooting'})

推荐阅读