1

我正在学习猫鼬,查看文档http://mongoosejs.com/docs/populate.html

然后我做了:

# initialize some TodoLists and their todos

l1 = new TodoList
    name: "List 1"
l2 = new TodoList
    name: "List 2"

t1 = new Todo 
    title: "Todo 1"
    desc: "Hello 1"
    list: l1._id
t2 = new Todo 
    title: "Todo 2"
    desc: "Hello 1"
    list: l1._id
t3 = new Todo 
    title: "Todo 3"
    dueOn: new Date 2012,6,1
    completedOn: new Date 2012,6,1
    list: l1._id
t4 = new Todo 
    title: "Todo 4"
    desc: "Hello 4"
    list: l2._id

# save all
async.parallel [
    (done) -> l1.save(done)
    (done) -> l2.save(done)
    (done) -> t1.save(done)
    (done) -> t2.save(done) 
    (done) -> t3.save(done)
    (done) -> t4.save(done)
], (err) -> 
    if !err
            # debugging
    Todo.find {}, (err, todos) ->
        console.log todos
            # the populate
    TodoList.findOne({ name: "List 2" })
            .populate("todos")
            .exec (err, list) ->
                console.log list
                done()
    else
        done err

我得到的是这样的:

 [ { desc: 'Hello 1',
    list: 5026321c684d0a6b08000007,
    _id: 5026321c684d0a6b08000009,
    __v: 0 },
  { desc: 'Hello 1',
    list: 5026321c684d0a6b08000007,
    _id: 5026321c684d0a6b0800000a,
    __v: 0 },
  { dueOn: Sun Jul 01 2012 00:00:00 GMT+0800 (SGT),
    completedOn: Sun Jul 01 2012 00:00:00 GMT+0800 (SGT),
    list: 5026321c684d0a6b08000007,
    _id: 5026321c684d0a6b0800000b,
    __v: 0 },
  { desc: 'Hello 4',
    list: 5026321c684d0a6b08000008,
    _id: 5026321c684d0a6b0800000c,
    __v: 0 } ]
{ name: 'List 2',
  _id: 5026321c684d0a6b08000008,
  __v: 0,
  todos: [] }

Noice 最后一行,todos 没有填充,我希望它有 Todo 4?

4

2 回答 2

2

Refs 不是双向的。您已将 refs 保存到Todos 的 parent Lists,但您没有将Todos 的 refs 存储到List.todos数组中。

假设您的 List 架构类似于:

var ListSchema = new Schema({
  ...
  todos : [{ type: Schema.Types.ObjectId, ref: 'Todo' }]
});

然后你需要做一个list.todos.push(todo._id).

于 2012-08-11T18:31:27.400 回答
1

通过使用以下代码,您无需在 ListSchema 中添加 todos 键。只需在定义 ListSchema 后放入以下代码:

ListSchema.virtual('todos', {
    ref: 'Post',
    localField: '_id',
    foreignField: 'list'
});

现在在列表集合中填充待办事项。

ListModel.find({}).populate('todos').exec((err, lists) => {
    if (err) return res.status(500).json(err);

    return res.status(200).json(lists);
});
于 2017-09-11T05:12:56.767 回答