1

So this is an example of my schema I have for a user.

    id: String,
    email: String,
    slug: {
        type: Object,
        phrase: {type: String, default: null},
    },

When I want to define a new user and save that user, I would do the following;

const newUser = new User({
   id: 123,
   username: "CoolUser",
   email: "[email protected]"
});
                
newUser.save();

But this does not save the "slug" object, It was my understanding, that since I a default value for it, it would auto populate with that default value. What can I do to make it auto generate without having to define the whole schema again when saving a user?

2 Answers 2

1

You should add default for slug property, and not for his sub-property. Try changing your schema like this:

slug: {
  type: {
    phrase: { type: String },
  },
  default: {
    phrase: null 
  },
},
Sign up to request clarification or add additional context in comments.

9 Comments

I then have the issue of trying to set phrase to a string as default. Like if I want to set phrase: "" that works, but phrase: "Test" doesnt
Can you upload you code? default: { phrase: "Test" } should work.
Can you upload it in the question with formatting?
|
0

try this:

const subschema = new Schema({
  phrase: {type: String, default: null},
}, { _id: false });

and in your original schema:

  id: String,
  email: String,
  slug: {
    type: subschema,
    default: () => ({})
  },

this should do the trick.

1 Comment

This doesn't help that much and is confusing because you didn't explain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.