How can I insert a collection into another collection using mongoose?

I’m learning MongoDB/Mongoose by the docs and I’m trying to insert the second collection into the first collection, I know how to do it by using $lookup in mongo terminal, but I kind of confuse how to do it the same in mongoose. I’ve already tried populate() but it didn’t work either.

First Schema

const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
    useremail: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    phone: {
        type: String,
        required: true
    },
    detail: {
        type: mongoose.SchemaTypes.ObjectId,
        ref: 'Detail'
    }
});

module.exports = mongoose.model('User', userSchema, 'users');

Second Schema

const mongoose = require('mongoose');
const detailsSchema = mongoose.Schema({
    full_name: {
        type: String,
        required: true
    },
    birthday: {
        type: String,
        required: true
    },
    second_contact: {
        type: Number,
        required: false
    },
    gender: {
        type: String,
        required: true
    },
    user: {
        type: mongoose.SchemaTypes.ObjectId,
        ref: 'User',
        required: true
    }
});

The route

const express = require('express');
const router = express.Router();
const Users = require('../models/user');
const Detail = require('../models/details');

router.post('/register', async(req, res) => {
    const { useremail, password, phone, full_name, birthday, gender } = req.body;
    try {
        let user = await Users.create({ useremail, password, phone });
        Users.findOne({ useremail }).populate('detail');

    } catch (err) {
        res.status(422).send(err);
        console.log(err);
    }
});

module.exports = router;

What I want is to create a new user along with its detail

I think your “insert collection into collection” statement is not what you want here, and calling it “insert documents into document” would be a better choice.

I am not mongoose expert, but it seems populate changes your client-side document, not on the server side. it seems it needs some already created documents with _id fields or returns null if the id does not match. then if your client side population does fine (you can check by printing logs as examples use) then you can use save method to add new updated document back into database.

but if you want to create completely new document, this is not the way how you would do it. first start exporting “Details” model as you did for “User” model. then create the details object as you did for the user object but use this user’s id as it is a required field for details object. now you may just “save” them in their respective collections and later use “$lookup” or “populate” to merge when needed.

and more on that, if what you want is to embed details into a user document, then you need serious schema design changes.