Население массива в мангусте - PullRequest
0 голосов
/ 01 октября 2019

Как мне заполнить массив "восхождений", помогите мне, пожалуйста.

{"_id":"5d92775ab93e250910838d98",
"seminars":["5d854deecfed0e2494b03e38","5d85533e56fa1c24588824ff"],
"ascents":[
{"_id":"5d8bd237f55e4326a4faf7d0","dateAscent":"2019-09-20T00:00:00.000Z"},
{"_id":"5d8bd250f55e4326a4faf7d1","dateAscent":"2019-09-20T00:00:00.000Z"},
{"_id":"5d8bd258f55e4326a4faf7d2","dateAscent":"2019-09-20T00:00:00.000Z"},
{"_id":"5d8bd26af55e4326a4faf7d3","dateAscent":"2019-0920T00:00:00.000Z"}
],
"status":true,
"user":"5d84f154d275fd125835b4ec","__v":17
}

моя модель:

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


var profileSchema = new Schema({
    user: { type: Schema.Types.ObjectId, ref: 'User', required: true },
    seminars: [{ type: Schema.Types.ObjectId, ref: 'Seminar', required: false }],
    ascents: [{ascent:{ type: Schema.Types.ObjectId, ref: 'Ascent', required: false },dateAscent:{ type: Date, required: true, default: Date.now }}],
    status: { type: Boolean, default: true }
});


module.exports = mongoose.model('Profile', profileSchema);

кто-токто может мне помочь как я могу это сделать?

1 Ответ

1 голос
/ 03 октября 2019

Попробуйте разделить определение схемы Ascent, чтобы она имела собственную модель

const ascentSchema = new Schema({
    dateAscent:{ 
        type: Date, 
        required: true, 
        default: Date.now 
     }
})

module.exports = mongoose.model('Ascent',ascentSchema  )

Тогда схема вашего профиля будет выглядеть следующим образом:

var profileSchema = new Schema({
    user: { type: Schema.Types.ObjectId, ref: 'User', required: true },
    seminars: [{ type: Schema.Types.ObjectId, ref: 'Seminar', required: false }],
    ascents: [{type: Schema.Types.ObjectId, ref: 'Ascent'}],
    status: { type: Boolean, default: true }
});

module.exports = mongoose.model('Profile', profileSchema);

К заполнить ascents Вы должны убедиться, что добавили действительный _ids в массив ascents при добавлении в новый документ Ascents.

При написании запроса, чтобы заполнить массив ascentsс соответствующими документами вы сделаете это:

Profile.find().
  populate({
    path: 'ascents',
    match: { }, //you can even filter the documents in the array using this match option
    // Explicitly exclude `_id`
    select: '-_id',
    options: { limit: 5 } //Also limit the amount of documents returned
  }).
  exec();

Дайте мне знать, если этот подход работает. Просто помните, что вам нужно вставить _ids в массив ascents, который находится отдельно от документа Profile, когда вы добавляете новый документ Ascent. См. пример из документов

...