How to get string value inside a Mongodb document? - mongodb

I have this document stored in mongodb document:
{
"_id":ObjectId("4eb7642ba899edcc31000001")
"hash":"abcd123"
"value":"some_text_here"
}
I am using NodeJS to access the database:
collection.findOne({'hash' : req.param('query') },
function(err, result){
console.log(res);
});
The result of this query is the whole document, however I need to get only the "value" text: "some_text_here"
How can this be done?

You can specify the fields that you are interested in (_id will always be returned, though):
collection.findOne({'hash': req.param('query') },
{fields: ['value'] },
callbackFunction );

You can do it such way:
collection.findOne({'hash' : req.param('query') },
function(err, result){
console.log(result.value);
});

Related

insert element into db only if it doesnt exist

Hy i am using mongoose.
I have this query that inserts about 30 elements into my database:
await Code.insertMany(information);
Information looks like:
[
{
discount: 20,
url: '...',
code: "...",
sponsorUrl: "...",
sponsorAccount: "..."
},
]
The url is unique. I want to add again 30 items into the database but it could be that 10 items from 30 are already saved in the database
How can i achieve that? I could loop it but is there an better solution?
I dont want to have duplicated urls
The upsert = true option creates the object if the url does not already exist in a document in the collection.
for (var i of information){
Code.update(
{'url' : i.url },
{$set : i},
{upsert : true, multi : true},
function(err, doc){
if(err) throw err;
console.log(doc);
}
)
}

mongo db findOneAndUpdate not returning document but updating it

findOneAndUpdate updates the document but returns with the error
collection.findOneAndUpdate(
{ verificationHash: req.query.hash },
{ $unset: {verificationHash: ''}}).then((err, user) => {//some code}
);
in this case my document is updated but user in callback is always undefined and content of error looks like
{
lastErrorObject: {n:1, updatedExisting: true},
value: document,
ok: 1
}
Am i missing something here or is this how the object in the callback is returned?
When executing .findOneAndUpdate in mongoDB then use {returnNewDocument: true} or if using mongoose you can use {new : true}
Set the returnNewDocument as true and you will get updated document.
collection.findOneAndUpdate(
{ verificationHash: req.query.hash }, // query
{ $unset: {verificationHash: ''}}, // update condition
{ returnNewDocument: true }, // returns updated document
function (err, documents) {
res.send({ error: err, affected: documents });
db.close();
}
)

How to save / update multiple documents in mongoose

I am reading all documents of a specific schema from Mongoose. Now in my program I am doing some modifications to the results I got from Mongoose over time. Something like this:
var model = mongoose.model("Doc", docSchema);
model.find(function(err, result){
// for each result do some modifications
});
How can I send all the results back to the database to be saved? Currently I am iterating the documents and doing a save() on every document. I think there must be a better way. But currently I only find information on updating documents IN the database without returning them. Or bulk updates which do the SAME to update to each document.
You can use update query with multi:true which update all documents in your db.
please find below reference code,
model.update({ "_id": id }, { $set: { "Key": "Value" } }, { multi: true }, function (err, records) {
if (err || !records) {
return res.json({ status: 500, message: "Unable to update documents." });
} else {
return res.json({ status: 200, message: "success" });
}
});
If you are trying to make the same change to each document in the results, you could do something like this:
model.update({ _id: { $in: results.map(doc=>doc._id) }}, { yourField: 'new value' }, { multi: true })

Get all fields names in a mongodb collection?

I'm coding a mongoose schema so I need a list of possible field in my collection.
Please how can I display all fields names in a specific collection, thank you.
switch to the db you're using and type:
mr = db.runCommand({
"mapreduce" : "myCollectionName",
"map" : function() {
for (var key in this) { emit(key, null); }
},
"reduce" : function(key, stuff) { return null; },
"out": "myCollectionName" + "_keys"
})
once you get result, type:
db[mr.result].distinct("_id")
and you will get a list of fields names.

Mongodb in operator in find Query

I have a query as mentioned below.
var projstat = ['A' , 'B'];
Post.native(function(err, collection) {
if (err)
console.log(err);
collection.find({
'status': {
"$in": projstat
}
}, {multi: true}, function(err, result) {
console.log(result);
if (req.isSocket) {
return res.json(result);
}
});
});
Please correct me if i am wrong as it doesnot return any results. Please help.
You're not using the native find correctly; rather than using a callback as an argument (like Waterline does), you chain the call to toArray and use the callback as its argument:
collection.find({
'status': {
"$in": projstat
}
}).toArray(function(err, results) {...});
Docs for the native Mongo driver are here.
However, the more important point in this case is that you don't need native at all. You can use the regular Waterline find, which automatically does an in query when an attribute is set to an array:
Post.find({status: projstat}).exec(function(err, results) {...});