Repopulate array of docs after update of this docs

17 views
Skip to first unread message

Павел Климашкин

unread,
Nov 8, 2013, 11:55:58 AM11/8/13
to mongoo...@googlegroups.com
Hello! Faced with the problem

I have long-live object of User model, wich I can save several times during its life. Each user have array of Region model, which i populate when querying User.
So, If I need to change array of Regions, I do it through user.update (because of https://github.com/LearnBoost/mongoose/wiki/3.6-Release-Notes#prevent-potentially-destructive-operations-on-populated-arrays).
But after that i need somehow to populate for user new regions. And I can't. Second user.populate returns same array of doc's as first time. What can I do?

var User = new mongoose.Schema({
login: {type: String, required: true, index: { unique: true }},
        regions: [{type: Schema.Types.ObjectId, ref: 'Region'}]
});
var Region = new Schema({
        cid: {type: Number, index: {unique: true}}
});

user.populate({path: 'regions', select: {_id: 0, cid: 1, title_en: 1, title_local: 1}}, function (err, user) {
        console.log(user.regions); // <-- [{cid: 1}, {cid: 2}]

        user.update({$set: {regions: some_new_ids }}, function (err, numberAffected, raw) {
                user.populate({path: 'regions', select: {_id: 0, cid: 1, title_en: 1, title_local: 1}}, function (err, user) {

                     console.log(user.regions); // <-- AGAIN [{cid: 1}, {cid: 2}]

                 });
        });

});

Павел Климашкин

unread,
Nov 8, 2013, 1:33:56 PM11/8/13
to mongoo...@googlegroups.com
I know how to resolve this.
user.regions = some_new_ids
need to be inserted before second populate

But if I do user.save after it, then array in database becomes with only one element - null !
Is this a bug?

пятница, 8 ноября 2013 г., 20:55:58 UTC+4 пользователь Павел Климашкин написал:
Reply all
Reply to author
Forward
0 new messages