2016-11-21 50 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