如何使用NodeJS与mongo Db中的用户和给定记录进行关联

时间:2018-08-14 11:22:37

标签: node.js mongodb

我是NodeJ的新手,并且在Node中有一个后端,该后端使用Mongo Db作为数据库。我可以在后端执行CRUD操作,问题是当我对所有电影进行GET操作时,这就是响应

{
    "status": "success",
    "message": "Movies list found!!!",
    "data": {
        "movies": [
            {
                "id": "5b72b2663911d82018cb81c3",
                "name": "Iron Man",
                "released_on": "2018-05-12T00:00:00.000Z"
            }      
        ]
    }
}

在上述情况下,我不知道是谁创建了电影,所以我想要这样的东西:

 {
        "status": "success",
        "message": "Movies list found!!!",
        "data": {
            "movies": [
                {
                    "id": "5b72b2663911d82018cb81c3",
                    "name": "Iron Man",                 
                    "released_on": "2018-05-12T00:00:00.000Z"
                    "creating_user" : [
                      //informations regarding the user who created the movie in the db
                   ]
                }      
            ]
        }
    }

为此,我有以下模型:

UserModel

const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const saltRounds = 10;

//Define a schema
const Schema = mongoose.Schema;

const UserSchema = new Schema({
    name: {
        type: String,
        trim: true,
        required: true,
    },
    email: {
        type: String,
        trim: true,
        required: true
    },
    password: {
        type: String,
        trim: true,
        required: true
    }
});
// hash user password before saving into database
UserSchema.pre('save', function (next) {
    this.password = bcrypt.hashSync(this.password, saltRounds);
    next();
});
module.exports = mongoose.model('User', UserSchema);

电影模型

const User = require("../models/users")
const mongoose = require('mongoose');
//Define a schema
const Schema = mongoose.Schema;

const MovieSchema = new Schema({
    name: {
        type: String,
        trim: true,
        required: true,
    },
    released_on: {
        type: Date,
        trim: true,
        required: true
    },
    creating_user:[{type: Schema.Types.ObjectId, ref: 'User'}]
});
module.exports = mongoose.model('Movie', MovieSchema)

这是我的控制人

const movieModel = require('../models/movies');
const usersModel = require('../models/users');
module.exports = {

  create: function (req, res, next) {
    movieModel.create({ name: req.body.name, released_on: req.body.released_on, creating_user: "DONT KNOW WHAT TO PUT HERE" }, function (err, result) {
      if (err)
        next(err);
      else
        res.json({ status: "success", message: "Movie added successfully!!!", data: null });

    });
  },
}

总而言之,我的问题是,为了保存用户信息以及电影信息,我应该在控制器中放置什么?

1 个答案:

答案 0 :(得分:0)

创建电影时,您需要在create_user字段中输入userId(用户的mongo _id)。

const movieModel = require('../models/movies');
const usersModel = require('../models/users');
module.exports = {

  create: function (req, res, next) {
    let userId=//get userId from req or auth token if you are using jwt
    movieModel.create({ name: req.body.name, released_on: 
        req.body.released_on, creating_user: userId }, function (err, result) {
      if (err)
        next(err);
      else
        res.json({ status: "success", message: "Movie added successfully!!!", data: null });

    });
  },
}

,当您获得所有电影列表时,您将必须填充creation_user以便获取用户记录:

  movieModel.find({}).populate('creating_user')
   .exec(function (err, item) {
    //do your stuff here
    });