Is an ObjectId automatically generated for a nested object?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Is an ObjectId automatically generated for a nested object?



My schema is as follows:


const MessageType =
// ...
oAuth: provider: String, id: String ,
attachments: [ name: String, contentType: String ],
// ...

MessageSchema = new mongoose.Schema(MessageType, timestamps: true);
Messages = mongoose.model("Message", MessageSchema);



When I insert a new Message document using Messages.create, an ObjectId (_id) is also generated for attachments, in addition to my name and contentType fields, ie:


Messages.create


ObjectId


_id


attachments


name


contentType


[ name: "xxx", contentType: "yyy", _id: zzzzzz ]



Why is this happening, for attachments but not oAuth?


attachments


oAuth




2 Answers
2



You can define _id : false in attachments array.


_id : false


const MessageType =
// ...
attachments: [ name: String, contentType: String, _id: false ],
// ...



For avoiding that the _id was generated you must set the option _id: false, Also if you don't want to save the empty attachments object, you need to set default: undefined.


const MessageTypeSchema = new mongoose.Schema(
oAuth:
type: String
,
attachments:
type: [

type: String

],
_id: false,
default: undefined

);



Here the code that I used to test:


console.log('-------- Document with attachments --------');
new MessageTypeModel(
oAuth:'xxxxxxxxxxxxx',
attachments: ['teste.png','teste2.jpg']
).save().then(result =>
console.log(result);
);

console.log('-------- Document without attachments --------');
new MessageTypeModel(
oAuth:'xxxxxxxxxxxxx'
).save().then(result =>
console.log(result);
);



And here the result of execution:



test execution





My question was why does it generate _id for attachments but not oAuth? The _id was in the attachments object, in addition to one in the main document.
– Old Geezer
3 mins ago



_id


attachments


oAuth


_id


attachments






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS