Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7432127
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T09:24:28+00:00 2026-05-29T09:24:28+00:00

The two types of objects seem to be so close to one another that

  • 0

The two types of objects seem to be so close to one another that having both feels redundant. What is the point of having both schemas and models?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T09:24:29+00:00Added an answer on May 29, 2026 at 9:24 am

    EDIT: Although this has been useful for many people, as mentioned in the comments it answers the "how" rather than the why. Thankfully, the why of the question has been answered elsewhere also, with this answer to another question. This has been linked in the comments for some time but I realise that many may not get that far when reading.

    Often the easiest way to answer this type of question is with an example. In this case, someone has already done it for me 🙂

    Take a look here:

    http://rawberg.com/blog/nodejs/mongoose-orm-nested-models/

    EDIT: The original post (as mentioned in the comments) seems to no longer exist, so I am reproducing it below. Should it ever return, or if it has just moved, please let me know.

    It gives a decent description of using schemas within models in mongoose and why you would want to do it, and also shows you how to push tasks via the model while the schema is all about the structure etc.

    Original Post:

    Let’s start with a simple example of embedding a schema inside a model.

    var TaskSchema = new Schema({
        name: String,
        priority: Number
    });
     
    TaskSchema.virtual('nameandpriority')
        .get( function () {
            return this.name + '(' + this.priority + ')';
        });
     
    TaskSchema.method('isHighPriority', function() {
        if(this.priority === 1) {
            return true;
        } else {
            return false;
        }
    }); 
     
    var ListSchema = new Schema({
        name: String,
        tasks: [TaskSchema]
    });
     
    mongoose.model('List', ListSchema);
     
    var List = mongoose.model('List');
     
    var sampleList = new List({name:'Sample List'});
    

    I created a new TaskSchema object with basic info a task might have. A Mongoose virtual attribute is setup to conveniently combine the name and priority of the Task. I only specified a getter here but virtual setters are supported as well.

    I also defined a simple task method called isHighPriority to demonstrate how methods work with this setup.

    In the ListSchema definition you’ll notice how the tasks key is configured to hold an array of TaskSchema objects. The task key will become an instance of DocumentArray which provides special methods for dealing with embedded Mongo documents.

    For now I only passed the ListSchema object into mongoose.model and left the TaskSchema out. Technically it’s not necessary to turn the TaskSchema into a formal model since we won’t be saving it in it’s own collection. Later on I’ll show you how it doesn’t harm anything if you do and it can help to organize all your models in the same way especially when they start spanning multiple files.

    With the List model setup let’s add a couple tasks to it and save them to Mongo.

    var List = mongoose.model('List');
    var sampleList = new List({name:'Sample List'});
     
    sampleList.tasks.push(
        {name:'task one', priority:1}, 
        {name:'task two', priority:5}
    );
     
    sampleList.save(function(err) {
        if (err) {
            console.log('error adding new list');
            console.log(err);
        } else {
            console.log('new list successfully saved'); 
        }
    });
    

    The tasks attribute on the instance of our List model (sampleList) works like a regular JavaScript array and we can add new tasks to it using push. The important thing to notice is the tasks are added as regular JavaScript objects. It’s a subtle distinction that may not be immediately intuitive.

    You can verify from the Mongo shell that the new list and tasks were saved to mongo.

    db.lists.find()
    { "tasks" : [
        {
            "_id" : ObjectId("4dd1cbeed77909f507000002"),
            "priority" : 1,
            "name" : "task one"
        },
        {
            "_id" : ObjectId("4dd1cbeed77909f507000003"),
            "priority" : 5,
            "name" : "task two"
        }
    ], "_id" : ObjectId("4dd1cbeed77909f507000001"), "name" : "Sample List" }
    

    Now we can use the ObjectId to pull up the Sample List and iterate through its tasks.

    List.findById('4dd1cbeed77909f507000001', function(err, list) {
        console.log(list.name + ' retrieved');
        list.tasks.forEach(function(task, index, array) {
            console.log(task.name);
            console.log(task.nameandpriority);
            console.log(task.isHighPriority());
        });
    });
    

    If you run that last bit of code you’ll get an error saying the embedded document doesn’t have a method isHighPriority. In the current version of Mongoose you can’t access methods on embedded schemas directly. There’s an open ticket to fix it and after posing the question to the Mongoose Google Group, manimal45 posted a helpful work-around to use for now.

    List.findById('4dd1cbeed77909f507000001', function(err, list) {
        console.log(list.name + ' retrieved');
        list.tasks.forEach(function(task, index, array) {
            console.log(task.name);
            console.log(task.nameandpriority);
            console.log(task._schema.methods.isHighPriority.apply(task));
        });
    });
    

    If you run that code you should see the following output on the command line.

    Sample List retrieved
    task one
    task one (1)
    true
    task two
    task two (5)
    false
    

    With that work-around in mind let’s turn the TaskSchema into a Mongoose model.

    mongoose.model('Task', TaskSchema);
     
    var Task = mongoose.model('Task');
     
    var ListSchema = new Schema({
        name: String,
        tasks: [Task.schema]
    });
     
    mongoose.model('List', ListSchema);
     
    var List = mongoose.model('List');
    

    The TaskSchema definition is the same as before so I left it out. Once its turned into a model we can still access it’s underlying Schema object using dot notation.

    Let’s create a new list and embed two Task model instances within it.

    var demoList = new List({name:'Demo List'});
     
    var taskThree = new Task({name:'task three', priority:10});
    var taskFour = new Task({name:'task four', priority:11});
     
    demoList.tasks.push(taskThree.toObject(), taskFour.toObject());
     
    demoList.save(function(err) {
        if (err) {
            console.log('error adding new list');
            console.log(err);
        } else {
            console.log('new list successfully saved'); 
        }
    });
    

    As we’re embedding the Task model instances into the List we’re calling toObject on them to convert their data into plain JavaScript objects that the List.tasks DocumentArray is expecting. When you save model instances this way your embedded documents will contain ObjectIds.

    The complete code example is available as a gist. Hopefully these work-arounds help smooth things over as Mongoose continues to develop. I’m still pretty new to Mongoose and MongoDB so please feel free to share better solutions and tips in the comments. Happy data modeling!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Visual Studio solutions contain two types of hidden user files. One is the solution
Suppose that there're two types of packet in the chatting server. Those two packets
There are two types of query parameters binding in the Hibernate Query. One is
Mysql has two types that can hold boolean data, bit and bool. Bit(1) seems
Say I have two types of objects, Apples and Chainsaws . A user is
i seem to be having difficulties in accessing and comparing objects in NSMutableArrays in
I have a class that contains two arraylists which I'm trying to store objects
I have two websites, both using .Net framework 3.5. One website is hosting a
A strict equality operator will tell you if two object types are equal. However,
When comparing two objects (of the same type), it makes sense to have a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.