Mongo db,如何给对象_id另一个集合的文档

时间:2016-12-20 19:36:02

标签: node.js mongodb collections reference schema

我有2个名为User和Location的集合。在用户中,有一个位置_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();

1 个答案:

答案 0 :(得分:0)

首先,您的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;
}