2016-12-20 98 views
1

我有2个集合称为用户和位置。在用户中,有一个位置_id,这是一个Object。 Id还引用了位置集合。我的问题是我做错了什么?当我调用getUser函数时,我想查看用户信息和用户的位置信息。我需要做什么 ?Mongo db,如何给对象_id另一个集合的文档

用户模式

module.exports = (function userSchema() { 
    var Mongoose = require('mongoose'); 

    var userSchema = Mongoose.Schema({ 
     name: { 
      type: String, 
      require: true 
     }, 
     surname: { 
      type: String, 
      require: true 
     }, 
     tel: { 
      type: String, 
      require: true 
     }, 
     age: { 
      type: String, 
      require: true 
     }, 
     mevki_id: { 
      type: String, 
      require: true 
     }, 
     location_id: [{ 
      type: Mongoose.Schema.Types.ObjectId, 
      ref: 'locations' 
     }] 
    }); 

    var collectionName = 'users'; 

    var User = Mongoose.model(collectionName, userSchema); 

    return User; 
})(); 

用户控制器

function userController() { 
    var User = require('../models/UserSchema'); 

    this.createUser = function (req, res, next) { 
     var name = req.body.name; 
     var surname = req.body.surname; 
     var tel = req.body.tel; 
     var age = req.body.age; 
     var mevki_id = req.body.mevki_id; 
     var lok_id = req.body.lok_id; 

     User.create({ 
      name: name, 
      surname: surname, 
      tel: tel, 
      age: age, 
      mevki_id: mevki_id, 
      lok_id: lok_id 
     }, function (err, result) { 
      if (err) { 
       console.log(err); 
       return res.send({ 
        'error': err 
       }); 
      } else { 
       return res.send({ 
        'result': result, 
        'status': 'successfully saved' 
       }); 
      } 
     }); 
    }; 

    this.getUser = function (req, res, next) { 
     User.find() 
      .populate('lok_id') 
      .exec(function (err, result) { 
       if (err) { 
        console.log(err); 
        return res.send({ 
         'error': err 
        }); 
       } else { 
        return res.send({ 
         'USERS': result 
        }); 
       } 
      }); 
    }; 
    return this; 
}; 

module.exports = new UserController(); 

回答

0

首先,你schema是错误的:

var userSchema = new Mongoose.Schema({ 
    // ... 
    location_id: { type: [Mongoose.Schema.Types.ObjectId], ref: 'locations' } 
}) 

其次,在你的schema日e最后一个字段名称为location_id,而在您的控制器中,您将其更改为lok_id

因此,解决这个问题:

User.create({ 
    // ... 
    location_id: lok_id 
} 

这:

User 
    .find() 
    .populate('location_id') 

UPDATE 在你json最后一个字段名称是location_id,因此,也解决这个问题:

this.createUser = function (req, res, next) { 
    // ... 
    var lok_id = req.body.location_id; 
} 
+0

我真的很想你你的帮助,但它没有工作,实际上我不能创建用户。有没有我的json文件porblem: – MAD

+0

你可以请检查我更新的答案?如果它仍然不起作用,你能不能显示'console.log(req.body)'的结果? – willie17

+0

{ “名称”: “阿基夫”, “姓”: “Demirezen”, “电话”: “6056056”, “年龄”: “35”, “mevki_id”: “2”, “LOCATION_ID “:{ ”IL“:” 伊斯坦布尔”, “ILCE”: “beylikduzu” } } \t 我张贴的JSON文件中像以上,但结果是这样的: { “结果”:{ “__v”:0, “_id”:“5859f736cc66d64394141b2e”, “location_id” :[] }, “status”:“成功保存” } – MAD

相关问题