Ray Purchase
Ray Purchase

Reputation: 762

How to specify the _id field with Mongoose when creating a document in MongoDB?

I have an app where users log in using Firebase Auth and I then store the user details in MongoDB using Mongoose. This works fine. However, the _id of each document is currently random. I would like to specify the _id field as the uid from Firebase which I am already storing separately.

This is my Schema:

const UserSchema = new mongoose.Schema({
email: {
    type: String,
},
name: {
    type: String,
},
photoUrl: {
    type: String,
},
token: {
    type: String,
},
uid: {
    type: String,
},
})

I have tried seemingly all variations of the below but nothing seems to work:

_id: {
    type: mongoose.Schema.Types.ObjectId,
},

No errors are given, just nothing gets written to Mongo (it does if I don't include the _id field). Can anyone see what I'm doing wrong, please?

Upvotes: 1

Views: 1511

Answers (2)

Yahya Rehman
Yahya Rehman

Reputation: 331

Converting _id: String is not such a great idea because mongoose will store it as a string instead of by default as an objectId. Mongoose fetching works efficiently because of objectId's which correspond to their key structure. Firebase id doesnt do that unfortunately. So we cant convert our firebase id to mongoose id. Another issue is if you want to save it as a foreign key into another collection by the mongoose method type: Schema.Types.ObjectId with ref of another table it will not work.

In my opinion the best way is to use the key of mongoose to create firebase user because you will be dealing with mongoose for all database usage except firebase auth. And firebase id's dont have a strict uid structure. You ca create firebase uid with literally anything.

const uid = new mongoose.Types.ObjectId()._id
const firebaseUser = await admin.auth().createUser({ uid: uid.toString(), email: payload.email, password: payload.password });

Upvotes: 1

funkizer
funkizer

Reputation: 4897

This should do it, because FB Auth uid is not an ObjectId:

_id: {
    type: String
}

Upvotes: 3

Related Questions