Home > Net >  Mongoose populate replacing ObjectIds with empty array
Mongoose populate replacing ObjectIds with empty array

Time:01-30

I've been trying to use the mongoose populate function to connect two models. I can save an object but when trying to retrieve using populate the ObjectIds are just replaced with an empty array. Many questions seem to have been asked but none have a solution that worked for me

user.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Route = require('./route')

var passportLocalMongoose = require('passport-local-mongoose');

const postSchema = new Schema ({
    text: {
        type: String,
        default: '',
        required: true
    }
}, {
    timestamps: true
});


const UserSchema = new Schema({
    firstname: {
        type: String
    },
    posts: [postSchema],
    route: [{
        type: mongoose.Schema.Types.ObjectId, 
        ref: 'Route'
    }]
}, {
    timestamps: true
});

UserSchema.plugin(passportLocalMongoose);

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


module.exports = User;

route.js

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

const locationSchema = new Schema ({
    id: {
        type: Number,
        default: 0,
        required: true
    },
    address: {
        type: String,
        default: '',
        required: true
    },
    lat: {
        type: Number,
        default: 0,
        required: true
    },
    lng: {
        type: Number,
        default: 0,
        required: true
    }

},{ 
    timestamps: true })

const routeSchema = new Schema ({
    locations: [locationSchema],
    description: {
        journey1: {
            type: String,
            default: '',
            required: false
        },
        journey2: {
            type: String,
            default: '',
            required: false
        },
        journey3: {
            type: String,
            default: '',
            required: false
        },
        journey4: {
            type: String,
            default: '',
            required: false
        }
    }
}, {
    timestamps: true
});

module.exports = mongoose.model('Route', routeSchema);

within REST POST end point

User.findOne({_id: req.user._id}, function(err,user) {
        if(user) {

            var routed = new Route();
            routed.locations = req.body.locations;
            routed.description = req.body.description;

            user.route.push(routed);
            user.save()
            .then((user) => {
                res.statusCode = 200;
                res.setHeader('Content-Type', 'application/json')
                res.json(user)
            }, (err) => next(err))
        } else {
            console.log("errored")
            err = new Error('User '   req.body.username   ' not found');
            err.status = 404;
            return next(err);
        }
    })

within REST GET end point

User.findOne({_id: req.user._id})
    .populate('route')
    .then((user) => {
        if(user){
            console.log("user")
            console.log(user)
            console.log("routes")
            console.log(user.route)
            res.statusCode = 200;
            res.setHeader('Content-Type', 'application/json')
            res.json({success: true, routes: user.route});
        }
    }, (err) => next(err))
    .catch((err) => next(err));

If I remove populate I'll get something like

[
new ObjectId("61f053af7ba46267f4893f8f")
new ObjectId("61f053af7ba46267f4893f8f")
new ObjectId("61f053af7ba46267f4893f8f")
]

from the GET end point but adding it back in returns [].
My understanding is that in 'new Route()' I'm creating a new Route Object with an Id that gets stored in the User model/document(?). Then when I call populate mongoose searches the Route document for those Ids and converts them to the objects I want. The only issue I could think of is that I'm not creating the Route objects correctly and so no object is being stored with that Id which is why an empty array is returned when I come to try swap Ids with Route objects.
Any ideas or are we all just stumbling in the dark ?

CodePudding user response:

Not entirely sure this is the correct method but instead of instantiating a Route object as displayed I used the Route.create(...) method and then pushed that to the route array and now populate works as expected

  •  Tags:  
  • Related