Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in Web Technology by (47.6k points)

Using node.js, mongodb on mongoHQ and mongoose. I'm setting a schema for Categories. I would like to use the document ObjectId as my categoryId.

var mongoose = require('mongoose'); 

var Schema = mongoose.Schema, 

ObjectId = Schema.ObjectId; 

var Schema_Category = new Schema({ 

categoryId : ObjectId, 

title : String, 

sortIndex : String 

});

I then run

var Category = mongoose.model('Schema_Category'); 

var category = new Category(); 

category.title = "Bicycles"; 

category.sortIndex = "3"; 

category.save(function(err) { 

if (err) { 

throw err; 

console.log('saved'); 

mongoose.disconnect(); 

});

Notice that I don't provide a value for categoryId. I assumed mongoose will use the schema to generate it but the document has the usual "_id" and not "categoryId". What am I doing wrong?

2 Answers

0 votes
by (106k points)

If you want to set ObjectId as a data type in mongoose then you do want a nicely named UUID field, mongoose provides virtual properties that allow you to proxy (reference) a field.

Check out the code mentioned below:-

var mongoose = require('mongoose'); 

var Schema = mongoose.Schema, 

ObjectId = Schema.ObjectId; 

var Schema_Category = new Schema({ 

title : String, 

sortIndex : String 

}); 

Schema_Category.virtual('categoryId').get(function() {

return this._id; 

});

0 votes
by (107k points)

To set type as an ObjectId (so you may reference the author as the author of the book, for example), you may do like:

const Book = mongoose.model('Book', {

  author: {

    type: mongoose.Schema.Types.ObjectId, // here you have to set the author ID

                                          // from the Author colection, 

                                          // so you can reference it

    required: true

  },

  title: {

    type: String,

    required: true

  }

});

Related questions

0 votes
1 answer
asked Jan 5, 2020 in Web Technology by ashely (50.2k points)
0 votes
0 answers
0 votes
1 answer
0 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...