F
F
Fengol2019-03-01 10:33:17
MongoDB
Fengol, 2019-03-01 10:33:17

How to automate replacement of ObjectId with document?

const EmbeddedInformationSchema = Schema({
    description: String
});
const UserSchema = Schema({
    informations: [EmbeddedInformationSchema]
})
const EmbeddedInformation = mongoose.model('EmbeddedInformation', EmbeddedInformationSchema);
const User = mongoose.model('User', UserSchema);

const run = async ()=>{
    await mongoose.connect('mongodb://localhost/test');
    await mongoose.connection.db.dropDatabase();

    await EmbeddedInformation.create({description: 'a'});
    await EmbeddedInformation.create({description: 'b'});

    let informationAll = await EmbeddedInformation.find();

    let user = await User.create({informations: informationAll.map(item=>item._id)});

    console.log(user); 
}

run().catch(console.error)

How can I automate document embedding so that the following is displayed in the console?
{informations: [{description: 'a'}, {description: 'b'}]}

And most importantly, I only need to replace documents when EmbeddedInformation is stored exactly in User.
Also, I know how to do it with the logic in the hooks, but maybe there is a way to specify it at the topic level or when calling methods (save, create..)?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question