DB.collection('comments').find() not working - mongodb

findOne()
const solutionList = await CommentMicroserviceDB.collection('comments').findOne({organizationId: ObjectId('5eb393ee95fab7468a79d189')});
Working Fine:-
{
_id: 6364e934830dcc00b488848d,
type: 'DOUBTS',
typeId: 63622eb7ddf697001fdc7b0a,
organizationId: 5eb393ee95fab7468a79d189,
createdBy: 62d53063e34fe92f8a135818,
status: 'Active',
displayOrder: 2,
createdAt: 2022-11-02T09:27:25.000Z,
updatedAt: 2022-11-02T09:27:25.000Z,
text:'<!DOCTYPE html>\n<html>\n<head>\n</head>\n<body>\n<p>Notification beofer berrnern</p>\n</body>\n</html>'
}
find()
const solutionList = await CommentMicroserviceDB.collection('comments').find({organizationId: ObjectId('5eb393ee95fab7468a79d189')});
But when I try with find() function is not working and give me:-
Cursor {
pool: null,
server: null,
disconnectHandler: Store { s: [Object], length: [Getter] },
bson: BSON {},
ns: 'comment_service.comments',
cmd:
{ find: 'comment_service.comments',
limit: 0,
skip: 0,
slaveOk: true },
options:
{ readPreference: [ReadPreference],
skip: 0,
limit: 0,
topology: [Server] },
.....
.....
sortValue: undefined }
Why this is happening ?
findOne function is working perfectly but find not
i need find here because i need all docs with given organizationId
Can anyone tell me
Thanks!!!

db.collection.find() returns a Cursor which is A pointer to the result set of a query. Clients can iterate through a cursor to retrieve results.
Refer to official collection.find() documentation.
If you just want the array of documents, try appending .toArray() at the end of your find query.
Try this:
const solutionList = await CommentMicroserviceDB.collection('comments').find({
organizationId: ObjectId('5eb393ee95fab7468a79d189')
}).toArray();
Read more about .toArray() here

Related

Why paginate plugin and skip/limit don't work in that mongodb query?

const paginateScheme = new Schema({
posts: [ { img: String, description: String, liked: String, postComId: String, comments: [ { author: String, text: String } ] } ],
}, {collection: "usersData"});
paginateScheme.plugin(mongoosePaginate);
const myModel = mongoose.model("sample", paginateScheme);
app.put("/api/pagination", function(req, res){
const options = {
page: 1,
limit: 3,
collation: {
locale: 'en',
},
};
const query = User.find({mail: 'user2#example.com'}, {posts: 1 });
myModel.paginate( query , options, function (err, result) {
if(err) return console.log(err);
res.send(result);
});
});
where post array of objects which I want to paginate.
I checked this plugin works correctly. When I use Model.find({}) it paginates through outer objects without any problems. I tried to use skip + limit but it returned nothing.
this query returns:
{
docs: [ { _id: 601a8f013d86dc237468467c, posts: [Array] } ],
totalDocs: 1,
limit: 3,
totalPages: 1,
page: 1,
pagingCounter: 1,
hasPrevPage: false,
hasNextPage: false,
prevPage: null,
nextPage: null
}
you can using $slice for paginate a array like this(use async/await)
let result = await myModel.find({mail: 'user2#example.com'}, {posts: {$slice: [0, 3]}})

How to create record if it does not exist in mongodb during bulkWrite?

The server will receiving lots of data. And issue is that I need to create records if a field name of the record does not exist in the database.
I am using mongoose for performing operations with mongodb.
db.getDb(async function (error, db) {
await db._models.Model.bulkWrite(
values.map((value) => {
const instance = new db._models.Model({
__v: 0,
});
return {
updateOne: {
filter: {
title: value,
_datasetId: dataset._id,
},
update: {
$set: {
_id: instance._id,
_datasetId: dataset._id,
title: tag,
createdBy: user._id,
createdAt: date,
updatedAt: date,
__v: instance.__v,
},
},
upsert: true,
},
};
})
);
I do not want to update existing record, but to create record if it does not exist. (If record with title and _datasetId exist, it should skip the values).
How can I achieve this?
You have already set upsert:true , in case updateOne do not find the document specified by the filter it will perform insert instead of update...

Update a value on each document with a value existing on that document

Objective:
I would like to update each document's points_left with the document's max_points value.
Player.js (Schema)
import mongoose from 'mongoose';
let Schema = mongoose.Schema;
let PlayerSchema = new Schema({
player_id: {
type: String,
required: true
},
points_left: {
type: Number,
default: 0
},
max_points: {
type: Number,
default: 5
},
created_date:{
type: Date,
default: Date.now
},
});
let Player = mongoose.model("players", PlayerSchema);
export default Player;
cron.js (cron job that plays every 24 hours)
/** This is not actually updating **/
Player.updateMany(
{},
[{"$set": { points_left: "$max_points" }}]
)
The below query works on MongoDB via terminal.
db.players.update(
{},
[{"$set": {points_left: "$max_points"}}],
{ multi : true }
)
Expected: {player_id: 1, points_left: 5, max_points: 5, created_date: 1234567890}
Actual: {player_id: 1, points_left: 0, max_points: 5, created_date: 1234567890}
If your using an async function make sure you are using await before calling updateMany
await Player.updateMany(
{},
[{"$set": { points_left: "$max_points" }}]
);
If not execute the query or it will not run, .then() will also execute if you need a callback.
Player.updateMany(
{},
[{"$set": { points_left: "$max_points" }}]
).exec();
I found a work-around. This one cycles through all of the documents and saves the points_left to max_points
Player.find({})
.then( docs => {
docs.forEach(doc => {
doc.points_left = doc.max_points
doc.save();
})
});
```

Insert default values not working mongodb

I am using mongoose version 5.2.5 and here is the sample model of my order
....
let PlaceOrderSchema = new mongoose.Schema({
any: {}
}, { strict: false },
{ timestamps: { updatedAt: 'last_updated', createdAt: 'created' });
I am using the above model in main script with mongoose save and findOneAndUpdate.
In our production system , we are seeing many document that does not have last_updated key missing in the save document.
Here are sample code of the mongoose save method and findOneAndUpdate in our main script.We are seeing some of the documents have updated_at keys while very few of them does not have it while saving the document
let orderModel = require('./orderModel');
let newOrder = {
order_no: 1234
};
//save usage code
(new Order(newOrder).save({lean: true}, ()=> {
//do...something
}));
//findOneAndUpdate usage Code
let orderNo = 123
OrderModel.findOneAndUpdate({ order_no: orderNo },
{
$set: { items: [{product_id: 'abc', quantity: 1}] },
},
{ new: true, upsert: true },
(err, res) => {
//do_something
});
Can any one share why we have few documents are getting saved without updated_at?
You need to use option setDefaultsOnInsert: true during the update operation.
Docs
By default, mongoose only applies defaults when you create a new
document. It will not set defaults if you use update() and
findOneAndUpdate(). However, mongoose 4.x lets you opt-in to this
behavior using the setDefaultsOnInsert option.
OrderModel.findOneAndUpdate(
{ order_no: orderNo },
{ $set: { items: [{ product_id: "abc", quantity: 1 }] }},
{ new: true, upsert: true, setDefaultsOnInsert: true }
)

getting Readable { .. } instead of specific collection using find() on mongodb

I have a collection named 'EloVars' on my mongodb, with only one document:
{
"_id": {
"$oid": "5800f3bfdcba0f48d2c58161"
},
"nextPID": "0",
"TotalComprasions": "0"
}
I'm trying to get the value of nextPID this way:
var myDoc = db.collection('EloVars').find();
if(myDoc) {
console.log('What exactly am I getting here:')
console.log(myDoc)
req.body.pid = myDoc.nextPID;
}
When I look at the console i noticed that what I'm getting is not 'EloVars' collection... just weired long Readable:
Readable {
pool: null,
server: null,
disconnectHandler:
{ s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] },
bson: {},
ns: 'mydb.EloVars',
cmd:
{ find: 'mydb.EloVars',
limit: 0,
skip: 0,
query: {},
slaveOk: true,
readPreference: { preference: 'primary', tags: undefined, options: [Object] } },
options:
.....
.....
What is this readable and why am I getting it?
find() returns a cursor. You have to iterate the cursor to get the documents.
var cursor = db.collection('EloVars').find();
cursor.each(function(err, doc) {
console.log(doc);
});
Or you can convert it to an array to get the documents.
cursor.toArray(function(err, doc){
console.log(doc);
});
Why are you trying in this way? if there is not any specific reason and you just wanted to get "nextPID" the you can use below query:
db.collection('EloVars').findOne({},{_id:0, nextPID:1}).exec(function(err, doc) {
if(doc) {
console.log('What exactly am I getting here:')
console.log(myDoc)
req.body.pid = doc.nextPID;
}
})
P.S.: it'll get only one nextPID.
to get all:
db.collection('EloVars').find({},{_id:0, nextPID:1}).exec(function(err, docs) {
if(docs && docs.length){
// your code here
}
})