Ссылки между двумя коллекциями, не работающими на MongoDB - PullRequest
0 голосов
/ 05 февраля 2019

Я создаю пользовательское приложение узла и внедряю в него планировщик DHTMLX.У меня есть планировщик, работающий и показывающий события, единственная проблема в том, что каждый пользователь видит и редактирует тот же календарь, что и сейчас.

Я пытался создавать схемы со ссылками, но, похоже, он не работал.

модель player.js (схема каждого отдельного пользователя):

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now
  },
  calendar: {
    type: Schema.Types.ObjectId, ref: 'calendar'
  }
});

const User = mongoose.model('player', UserSchema);

module.exports = User;

модель calendar.js:

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;


    const schema = new Schema({
        text: {type: String, required = true},
        start_date: {type: Date, required = true},
        end_date:   {type: Date, required = true},
        user: {type: Schema.Types.ObjectId, ref = 'User', required = true}

    });

    const calendar = mongoose.model('calendar', schema);

    module.exports = calendar;

Реализация календарной части моего app.js

var db = require('mongoskin').db("myMongoDBCluster", { w: 0});
db.bind('calendar');


    app.use(express.static(path.join(__dirname, 'public')));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));

    app.get('/init', function(req, res){
        db.calendar.insert({ 
            text:"My test event A", 
            start_date: new Date(2018,8,1),
            end_date:   new Date(2018,8,5)
        });
        db.calendar.insert({ 
            text:"My test event B", 
            start_date: new Date(2018,8,19),
            end_date:   new Date(2018,8,24)
        });
        db.calendar.insert({ 
            text:"Morning event", 
            start_date: new Date(2018,8,4,4,0),
            end_date:   new Date(2018,8,4,14,0)
        });
        db.calendar.insert({ 
            text:"One more test event", 
            start_date: new Date(2018,8,3),
            end_date:   new Date(2018,8,8),
            color: "#DD8616"
        });

        res.send("Test events were added to the database")
    });


    app.get('/data', function(req, res){
        db.calendar.find().toArray(function(err, data){
            //set id property for all records
            console.log(err);
            for (var i = 0; i < data.length; i++)
                data[i].id = data[i]._id;

            //output response
            res.send(data);
        });
    });


    app.post('/data', function(req, res){
        var data = req.body;
        var mode = data["!nativeeditor_status"];
        var sid = data.id;
        var tid = sid;

        delete data.id;
        delete data.gr_id;
        delete data["!nativeeditor_status"];


        function update_response(err, result){
            if (err)
                mode = "error";
            else if (mode == "inserted")
                tid = data._id;

            res.setHeader("Content-Type","application/json");
            res.send({action: mode, sid: sid, tid: tid});
        }

        if (mode == "updated")
            db.calendar.updateById( sid, data, update_response);
        else if (mode == "inserted")
            db.calendar.insert(data, update_response);
        else if (mode == "deleted")
            db.calendar.removeById( sid, update_response);
        else
            res.send("Not supported operation");
    });

1 Ответ

0 голосов
/ 05 февраля 2019

Mongo - это нереляционная база данных, «ссылка» - это функция, предоставляемая mongoose.Чтобы использовать его, вы должны запросить через модели Мангуста (объекты, экспортированные из player.js и calendar.js)

var Calendar = require('./calendar');

Calendar.find()
  .then(function (data) {
    // ...
  });

Calendar.find({user: 'yourUserId'}) // query by specific user
  .then(function (data) {
    // ...
  });
...