我正在学习猫鼬,查看文档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?