Open In App

How does Query.prototype.j() work in Mongoose ?

Last Updated : 17 Mar, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The Query.prototype.j() function is used to request acknowledgement that this operation has been persisted to MongoDB’s on-disk journal.

Syntax: 

Query.prototype.j()

Parameters: This function has one val parameter of boolean type. 
Return Value: This function returns Query Object.
Installing mongoose : 

npm install mongoose

After installing the mongoose module, you can check your mongoose version in command prompt using the command. 

npm mongoose --version

After that, you can just create a folder and add a file for example, index.js as shown below.

Database: The sample database used here is shown below: 
 

Example 1: 
Filename: index.js 
 

javascript




const mongoose = require('mongoose');
  
// Database connection
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
});
  
// User model
const User = mongoose.model('User', { 
    name: { type: String },
    age: { type: Number }
});
  
const query = User.updateOne({name:"Gourav"}, { $set: {name: 'Geek'} }).j(true);
console.log("Above operation has been persisted to MongoDB's on-disk journal")


The project structure will look like this: 
 

Run index.js file using below command: 

node index.js

Output: 

Above operation has been persisted to MongoDB's on-disk journal

Example 2: 
Filename: index.js 
 

javascript




const express = require('express');
const mongoose = require('mongoose');
const app = express()
  
// Database connection
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
});
  
// User model
const User = mongoose.model('User', { 
    name: { type: String },
    age: { type: Number }
});
  
const query = User.updateOne({name:"Gourav"}, { $set: {name: 'Geek'} }).j(false);
console.log("Above operation has not been persisted to MongoDB's on-disk journal")
  
app.listen(3000, function(error ) {
    if(error) console.log(error)
    console.log("Server listening on PORT 3000")
});


The project structure will look like this: 
 

Run index.js file using below command: 

node index.js

Output: 

Server listening on PORT 3000
Above operation has not been persisted to MongoDB's on-disk journal

Reference: 
https://mongoosejs.com/docs/api/query.html#query_Query-j
 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads