0

Im not sure why Schema.ObjectId is not working on my model, I have the latest version of mongoose.

this is my model

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

var TeamSchema = new mongoose.Schema({
    team_name : {
        type: String,
        index : true
    },
    dateCreated : {
        type : Date
    },
    memberId : {
        type : Schema.Types.ObjectId
    }
});

var Team = module.exports = mongoose.model('Team', TeamSchema);


module.exports.createTeam = function(newTeam, callback){

    newTeam.save(function(err){
        if (err) throw err;
    });

}

I also tried this post still not working. can anyone help on this? thanks

this is the json file of my data, and its weird the memberId is not showing

[
  {
    "_id": "587da4a9141f1619f42ac66d",
    "dateCreated": "2017-01-17T04:59:21.000Z",
    "team_name": "Sample Team",
    "__v": 0
  }
]
Community
  • 1
  • 1
Joel Ralph
  • 53
  • 1
  • 8

1 Answers1

0

I do not see anything wrong with your schema.

Mongoose defines a new ObjectId only for _id field. For all other fields of type ObjectId you have to pass a new ObjectId value to it.

So if the field memberId is for holding an ObjectId that refers to a member in another collection (eg. members), you can pass the _id value of a member of members collection into memberId. (Also adding a ref in your schema to that collection would be helpful)

If memberId is a totally new ObjectId and not related to any other collection, then you can generate a new unique ObjectId with the function mongoose.Types.ObjectId() and save it to memberId field.

So do this before saving newMember:

newMember.memberId = mongoose.Types.ObjectId();

Hope that helps!

Santanu Biswas
  • 4,699
  • 2
  • 22
  • 21