How to create one to many association in sails.js with mongoDB, especially when the id is a string and not an ObjectId?

23 Views Asked by At

I am working with the Waterline ORM sails.js in my Node.js application, and I have two models, "Owners" and "Pets." The issue I'm facing is that the "id" field in the "Owners" model is an Object ID, while in the "Pets" collection, it is saved as a string.

Here's how the models are defined:

models/Pets.js

attributes:{
    ownerId: {
        model: "Owners",
        columnName: "user.owner_id",
    },
}
models/Owners.js

attributes:{
    pets: {
        collection: "Pets",
        via: "ownerId",
    },
}

Because of this mismatch in ID types, I'm having trouble fetching the owners of a pet using Waterline's built-in methods like .populate() or .findOne(). The automatic population is not working as expected due to the data type difference.

I've tried using .populate() and .findOne() like this:

Pets.findOne({ id: petId }).populate("ownerId").exec((err, pet) => {
    if (err) {
        // Handle error
    }
    console.log(pet.ownerId); // Returns null
});

Unfortunately, pet.ownerId is always returning null, and I suspect it's because of the mismatch between the ID types.

How can I handle this mismatch in ID types and make the .populate() functions work correctly? Any help or guidance would be greatly appreciated. Thank you!

0

There are 0 best solutions below