2016-11-21 117 views
0

我是新来的节点,我使用的是Feathersjs。 我试图用猫鼬填入做userstasks猫鼬在羽毛上填充

我的模型之间的关系:

user-model.js

const mongoose = require('mongoose'); 
const Schema = mongoose.Schema; 

const userSchema = new Schema({ 
email: {type: String, required: true, unique: true}, 
password: { type: String, required: true }, 
tasks: [{ type: Schema.Types.ObjectId, ref: 'Task' }], 
createdAt: { type: Date, 'default': Date.now }, 
updatedAt: { type: Date, 'default': Date.now } 
}); 

var Task = mongoose.model('Task', storySchema); 
const userModel = mongoose.model('user', userSchema); 

module.exports = userModel; 

task-model.js

const mongoose = require('mongoose'); 
const Schema = mongoose.Schema; 

const taskSchema = new Schema({ 
title: { type: String, required: true }, 
_creator : { type: String, ref: 'User' }, 
createdAt: { type: Date, 'default': Date.now }, 
updatedAt: { type: Date, 'default': Date.now } 
}); 

var User = mongoose.model('user', storySchema); 
const taskModel = mongoose.model('task', taskSchema); 

module.exports = taskModel; 

当我添加新任务,user.tasks仍为空:

> db.users.find().pretty() 
{ 
    "_id" : ObjectId("5832da6919756a0edc2dfc59"), 
    "email" : "[email protected]", 
    "password" : "$2a$10$DToGYQ8smdfsK4oJPXmcyOdIfxXEaQGO5P16AhzBlrpESUMt5baNi", 
    "updatedAt" : ISODate("2016-11-21T11:28:41.371Z"), 
    "createdAt" : ISODate("2016-11-21T11:28:41.371Z"), 
    "tasks" : [ ], 
    "__v" : 0 
    } 
> db.tasks.find().pretty() 
{ 
    "_id" : ObjectId("5832da7619756a0edc2dfc5a"), 
    "title" : "test", 
    "_creator" : "5832da6919756a0edc2dfc59", 
    "updatedAt" : ISODate("2016-11-21T11:28:54.470Z"), 
    "createdAt" : ISODate("2016-11-21T11:28:54.470Z"), 
    "__v" : 0 
} 

回答

0

MongoDB中没有连接,但有时我们仍然希望引用其他集合中的文档,就像在您的用例中一样。这是人口进来

所以,你可以使用mongoose如下尝试:

User     // Mongoose model 
.find({}) 
.populate('tasks') // Populate referenced attributes 
.exec()    // Executes the query and return Promise 

了解更多关于人口猫鼬: http://mongoosejs.com/docs/populate.html