2016-12-20 163 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

相關問題