猫鼬关系不是双向的

时间:2015-02-02 09:01:47

标签: express mongoose mean-stack

我无法在我的应用程序中使用我的Rides和Comments控制器之间建立关系(使用yeoman angular-fullstack生成器构建)。

评论模型:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var CommentSchema = new Schema({
  name: String,
  comment: String,
  active: Boolean,
  ride: { type: mongoose.Schema.Types.ObjectId, ref: 'Ride' }
});

module.exports = mongoose.model('Comment', CommentSchema);

骑行模式:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var RideSchema = new Schema({
  name: String,
  distance: String,
  climb: String,
  rating: String,
  active: Boolean,
  comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
});

module.exports = mongoose.model('Ride', RideSchema);

访问/ api / comments /给我一个正确的结果,包含一个相关的Ride:

{"_id":"54ce818f8c2889da58b01e19","name":"NAAM","comment":"COMMENT","ride":"54ce69647a78532057aa98e0","__v":0}]

访问/ api / rides /给出了以下结果,没有相应的注释:

[{"_id":"54ce69647a78532057aa98e0","name":"Ride test ingevuld","distance":"4000","climb":"1200","rating":"1","__v":0,"comments":[]}]

谁能告诉我我做错了什么?

2 个答案:

答案 0 :(得分:0)

就我而言,它并不像那样。你的评论得到了它,你的旅程得到了它的评论。我想,你应该删除

ride: { type: mongoose.Schema.Types.ObjectId, ref: 'Ride' }

并在评论中保留评论。

comments: ['Comment']

它是更客观的解决方案,因为它应该是为客观(层次)数据设计的MONGO DB。

答案 1 :(得分:0)

我的一个项目示例:

exports.insertRoom = function(req, res) {
var id =  req.body.id;

var r =  req.body.room;
var room = new Room({name: r.name});

Floor.update(
    {_id : id},
    {
        $push: { rooms: room}
    },
    {upsert:true},
    function(floor, err)
    {
            res.sendStatus(200);
    }
);

};