Search code examples
node.jsmongodbmongoose

Insert a document containing a field from another collection


I have these 2 models:

Role model (Role.js)

const mongoose = require ("mongoose");

const roleSchema = mongoose.Schema({
    role: {
        type : Number,
        required : true
    },
    description : {
        type : String,
        required : true         
    } 
});

module.exports = mongoose.model("Role", roleSchema);

I populate the Role collection:

db.Roles.insertMany([{_id: 1, description: "Read only"}, { _id: 2, description: "Read, write" }, { _id: 3, description: "Read, write, delete" }])

Admin model (Admin.js)

const mongoose = require ("mongoose");
const Role = require("./Role");

const adminSchema = mongoose.Schema({
    firstName : { 
        type : String,    
        required : true
    },
    lastName : {
        type : String,
        required : true
    },
    email : {
        type : String,
        required : true
    },
    dateCreate : { 
        type : Date, 
        default : Date.now 
    }, 
    role : {
        type : mongoose.Schema.Types.ObjectId,
        ref : "Role"
    }
})

module.exports = mongoose.model("Admin", adminSchema);

As you can see, the Admin model contains a field that is a reference to the Role _id in Role.js

Now I'm trying to insert a document in the Admin collection.

mongoose.connect("mongodb://127.0.0.1:27017/Test")
 
insertAdmin()
async function insertAdmin() { 
    try {       
        const role = Role.findOne({_id: 3});
        console.log("Role: " + role)

        const admin = await Admin.create({
            firstName : "Kate",
            lastName : "Eagan",
            email : "[email protected]",
            role : role._id            
        })

        console.log("Admin added");
    } catch (err) {
        console.log(err.message)
        console.log("Admin NOT added");
    }

    //console.log(admin);
}

All goes well, the admin is added, but when I do (using mongosh) :

db.admins.find()

all the admins have no role field, it's just not showing. I guess I'm not inserting it correctly in my insertAdmin() function?


Solution

  • I re-created your work here GitHub

    it just worked perfectly, seems that the problem is that when you try to assign the founded id of the role to the new admin that you want to create, it comes with **ObjectId**(xxxxxxxxxx) prefix and in that way it don't work as far as I know, you can check, another thing, can anyone knows the difference between

    mongoose.Types.ObjectId
    

    and

    mongoose.Schema.Types.ObjectId
    

    and one more thing to add is that if the role is required in the admin model you should add the option, so that you can check it with your existing code.