Mongoose Schema Embedded Document Default

后端 未结 1 1735
隐瞒了意图╮
隐瞒了意图╮ 2021-01-25 00:01

I am trying embed a document, so I guess a subdocument, into a Mongoose schema. I have been following this pattern that the Mongoose documentation suggests. My schemas look like

相关标签:
1条回答
  • 2021-01-25 00:47

    I believe the problem might lie in your dependency declarations. I used your code to declare the mongoose schemas, and it worked correctly, however you did not include your dependencies, or your create methods, so let me show you how I created the record and I hope that helps. You can also reference this Stack Overflow answer for dependency declaration of the ObjectId: How to set ObjectId as a data type in mongoose

    Here is my code:

    //contents of stackoverflow.js
    var mongoose = require('mongoose'),
    Schema = mongoose.Schema;
    var ObjectId = Schema.ObjectId;
    
    var CategoriesSchema = new Schema({
        name: { type: String, required: true, default: 'default' }
    });
    
    
    var PostSchmea = new Schema({
       title: { type: String, required: true, default: 'default title' },
       writtenBy: { type: ObjectId, required: true, default:     '55878003ebf4b06110ef2ff8' },
       publishedOn: { type: Date, default: Date.now },
       updatedOn: Date,
       published: { type: Boolean, required: true, default: false },
       content: { type: String, required: true, default: 'empty' },
       category: { type: [CategoriesSchema], default: [CategoriesSchema] },
       tags: [String],
       images: [String]
    });
    
    mongoose.model('Post', PostSchmea);
    mongoose.model('Categories',CategoriesSchema);
    

    I then declared the Schemas and models in my server.js file to run the code and create a record:

    //contents of my server.js file (or wherever you put your controllers)    
    var stack = require('./app/models/stackoverflow'),
    post = mongoose.model('Post');
    
    var v = new post({
      //Define your values here
    });
    
    v.save(function(err,docs) {
    if (err) {
       console.log(err)
    
    } else {
      console.log(docs)
    }
    });
    

    This successfully created the records with all of the defined default values. Hope that helped.

    0 讨论(0)
提交回复
热议问题