Mongoose is MongoDB driver module which provide REST features to build faster MongoDB apps with Nodejs.
Mongo Object Id
MongoDB object ID is an automatically generated multipurpose number. In our case we can use it to show up the document. In fact the Object ID consist of date and a unique random number.
The mongoose schema
const mongoose = require('mongoose');
const PostSchema = new mongoose.Schema({
title: {
type: String,
required: '{PATH} is required!'
},
content: {
type: String,
required: '{PATH} is required!'
},
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}, {
timestamps: true
})
module.exports = mongoose.model('Post', PostSchema);
Here the user field is an example for the Object ID field and the resulted document will look like the following
New Post:{ _id: 5fee99c33cbe8b25d0ced080, title: 'Happy New Year', content: 'Happy New Year MEssage', user: 5fe4ab1e69b8d525c44ec293, createdAt: 2021-01-01T03:40:51.340Z, updatedAt: 2021-01-01T03:40:51.340Z, __v: 0 }
Populate the user
Using the populate command we can get the complete User information which will be show as sub document/sub object. To populate the result we have to use the populate ,exec and create a caller function
Post.findById(post._id).populate('user').exec(function(error, post) { console.log('New post - > ' + post); })
and the resulted document will be
New post - > { "_id": "5fe6ca78443a4d0f54aafecf", "title": "Hosting", "content": "4 Month free hosting plans for 100 developer opens now", "user": { "_id": "5fe4db85a4896d069006601b", "name": "emma", "createdAt": "2020-12-24T18:18:45.224Z", "updatedAt": "2020-12-24T18:20:47.857Z", "__v": 1 }, "createdAt": "2020-12-26T05:30:32.715Z", "updatedAt": "2020-12-26T05:30:32.715Z", "__v": 0 }
That’s it. Following mongoose posts deserve your attention
- How to interact with input in Reactjs - How to handle state and event of input element in React apps
- How to populate multiple MongoDB objects on the same path in express-node - How to populate multiple objects in MongoDB in the same path
- How to populate selected fields in a mongo document path in expressjs - How to populate object in mongo doc at a specific path with specific fields
- How to populate and display nested mongo objectin express-node route - How to populate object in express-MongoDB app
- How to render mongo object in Reactjs - How to render MongoDB object/ObjectId in React/MERN app
- How to render list of mongo objects in React component - How to render list of mongo objects in Reactjs
- How to place custom route links in Reactjs component - How to place custom links to routes/page in Reactjs
- How to filter MongoDB object list in express-node app - How to filter a mongo object list in document in express-node app
- How to fix mongo object Type error in Reactjs - How to fix TypeError/undefined in React - MERN application
- How to create document using mongoose in express-node app - How to save MongoDB document to the collection using mongoose REST operations