[英]Mongo db, how to give object _id another collection's document
我有2個名為User和Location的集合。 在User中,有一個位置_id,這是一個Object
。 Id還引用了位置集合。 我的問題是我做錯了什么? 當我調用getUser函數時,我想查看用戶信息和用戶的位置信息。 我需要做什么 ?
用戶架構
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();
首先,您的schema
是錯誤的:
var userSchema = new Mongoose.Schema({
// ...
location_id: { type: [Mongoose.Schema.Types.ObjectId], ref: 'locations' }
})
其次,在您的schema
,最后一個字段名稱是location_id
而在控制器中,您將其更改為lok_id
。
所以,解決這個問題:
User.create({
// ...
location_id: lok_id
}
和這個:
User
.find()
.populate('location_id')
更新在你的json
,最后一個字段名是location_id
,因此,修復它:
this.createUser = function (req, res, next) {
// ...
var lok_id = req.body.location_id;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.