2017-09-06 47 views
0

我正在用mongoDB和NodeJS构建一个带Angular前端的应用程序。我目前有用户创建列表,然后其他用户在这些列表中响应出价,但希望包含这些响应者的数据。我很难在投标创建功能中包含该用户数据,但不确定其为何不拉。如何在我的猫鼬对象中包含来自另一个集合的数据?

这里是上市模式

var mongoose = require("mongoose"); 
var Schema = mongoose.Schema; 

var Bid = require('./bid'); 

var ListingSchema = new Schema({ 
    topic: String, 
    description: String, 
    budget: String, 
    location: String, 
    req1: String, 
    req2: String, 
    req3: String, 
    created: String, 
    dateReq: String, 
    uid: String, 
    bids: [Bid.schema] 
}) 

这是怎么了我目前创建商家

function create(req, res) { 
    db.User.findById(req.user, function (err, user) { 
    if (err) {console.log(err);} 
    var newListing = new db.Listing(req.body); 
    newListing.uid = user._id 
    newListing.save(function (err, savedListing) { 
     if (err) { 
     res.status(500).json({ error: err.message }); 
     } else { 
     user.listings.push(newListing); 
     user.save(); 
     res.json(savedListing); 
     } 
    }); 
    }); 
}; 

这是新的出价。出于某种原因,db.User信息没有被拉动,我的控制台日志显示一个空白对象。 (是的,我的评论吧)

function create(req, res) { 
    // db.User.findById(req.user, function (err, user) { 
    // console.log(req.user); 
    // if (err) {console.log(err);} 
     db.Listing.findById(req.params.listingId, function(err, foundListing) { 
     var newBid = new db.Bid(req.body); // add data validation later 
    // newBid.uid = user._id 
     foundListing.bids.push(newBid); 
     foundListing.save(function(err, savedBid) { 
     res.json(newBid); 
     }); 
     }); 
    }); 
}; 
+0

做当您登录'req.user你会得到什么来自回调的''和'user'对象 – turmuka

+1

您确实意识到这实际上并不存储在“其他集合”中。所以你的问题题目不正确,或者你错过了整个概念。您所包含的模式是“嵌入式”,这意味着数据包含在父文档的数组中,而不是其他任何地方。您还需要显示“Bid”的定义以及实际发送到“req.body”的内容 –

回答

0

尝试使用USER_ID作为参照对象,并填充它需要的时候你的架构应该是有点像这个

var ListingSchema = new Schema({ topic: String,description: String, budget: String, location: String, req1: String, req2: String, req3: String, created: String, dateReq: String,//THIS CREATES A REFERENCE TO THE SCHEMA USER AND TO USE THIS YOU CAN POPULATE IT.. uid: {type:Schema.type.ObjectId,ref:User}, bids: [Bid.schema]}) 
相关问题