Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding mongoose [Schema.Types.Mixed]

Is the below schema defined correctly or does writing need to be writing: [Schema.Types.Mixed] or writing: [{}]?

That is, if you have an array of dictionaries -- [{},{},{}] -- one can't predefine the internal structure unless you create another schema and embed it. Is that the right interpretation of the docs?

http://mongoosejs.com/docs/schematypes.html

var blogSchema = new mongoose.Schema({
  title:  String,
  writing: [{
        post: String,
        two: Number,
        three : Number,
        four  : String,
        five : [{  a: String,
                    b : String,
                    c  : String,
                    d: String,
                    e: { type: Date, default: Date.now }, 
                }]
  }],
});

Thanks.

like image 697
cathy.sasaki Avatar asked May 14 '13 00:05

cathy.sasaki


People also ask

What is mixed type in Mongoose?

Mixed }); const Any = new Schema({ any: mongoose. Mixed }); Since Mixed is a schema-less type, you can change the value to anything else you like, but Mongoose loses the ability to auto detect and save those changes. To tell Mongoose that the value of a Mixed type has changed, you need to call doc.

What is Mongoose schema types ObjectId?

In mongoose, the ObjectId type is used not to create a new uuid, rather it is mostly used to reference other documents. Here is an example: var mongoose = require('mongoose'); var Schema = mongoose. Schema, ObjectId = Schema.


1 Answers

That schema is fine. Defining an object within an array schema element is implicitly treated as its own Schema object. As such they'll have their own _id field, but you can disable that by explicitly defining the schema with the _id option disabled:

var blogSchema = new mongoose.Schema({
    title: String,
    writing: [new Schema({
        post: String,
        two: Number,
        three : Number,
        four  : String,
        five : [new Schema({ 
            a: String,
            b: String,
            c: String,
            d: String,
            e: { type: Date, default: Date.now }, 
        }, {_id: false})]
    }, {_id: false})],
});
like image 137
JohnnyHK Avatar answered Oct 10 '22 10:10

JohnnyHK