logo
down
shadow

Mongodb find is not working with the Objectid


Mongodb find is not working with the Objectid

By : Rahul Sharma
Date : November 17 2020, 11:52 AM
This might help you Your webpageids are strings while the _ids that you are searching with are ObjectIds. Your find does not match any results because there are no documents in the results table which have ObjectId values for the "webpageid" element.
There are two solutions as I see it.
code :
...
for(var i = 0; i < docs.length; i++) {
    var docId = docs[i]._id.toString(); // create a string
    db.get('results').findOne({'webpageid':docId}, function(err, doc)
    ...
"webpageid" : "\"54960a916ecb16dc3c4880e8"


Share : facebook icon twitter icon
Find a document with ObjectID in mongoDB

Find a document with ObjectID in mongoDB


By : user3421919
Date : March 29 2020, 07:55 AM
To fix the issue you can do Pretty sure you have to use a MongoId object, eg
code :
$item = $collection->findOne(array(
    '_id' => new MongoId('4e49fd8269fd873c0a000000')));
MongoDB: find by one objectId in array

MongoDB: find by one objectId in array


By : KPRDave
Date : March 29 2020, 07:55 AM
like below fixes the issue I'm having trouble with query the DB, I want to get all element that the have for example: admin "54bd13864ec56c7c12310a79" in the admins array, , Convert the id string to ObjectId:
code :
var mongoose = require('mongoose'),
    trainerId = '54bd13864ec56c7c12310a79';
var id = mongoose.Types.ObjectId(trainerId);

GroupSchema.find({'admins': id });
Find all with related objectId name in MongoDB

Find all with related objectId name in MongoDB


By : user3837719
Date : March 29 2020, 07:55 AM
mongodb $nin on ObjectId not working

mongodb $nin on ObjectId not working


By : Robert Steury
Date : March 29 2020, 07:55 AM
may help you . {_id: {$nin: items}} expects an array of ObjectIds and from what I can see you're passing an array of documents and what's even worse you seem to be telling mongo not to select _id in your findquery.
This is how I would go about this.
code :
var items = db.listsProducts.find({_id: {$exists: true}}, {product: true, _id: true}).toArray();

var itemIds = items.map(function(i) {
    return i._id;
});

db.products.update({_id: {$nin: itemIds}}, {$set: {status: 'inactive'}}, {multi: true});
MongoDB: How to find and replace ObjectId across collection

MongoDB: How to find and replace ObjectId across collection


By : user3625583
Date : March 29 2020, 07:55 AM
hop of those help? I ended up doing this on our NodeJS server. To run, just call 'replaceDocument.' If people find it useful, I may make it into an npm package. I haven't seen this functionality anywhere.
code :
let toReplace = null;
let replacement = null;
let searchKey = null;

function replaceReferencesInDoc(document) {
  let mongooseUpdateObject = null;

  function checkForSearchKey(anyType, path, currentKey) {

    if (currentKey === searchKey && anyType + "" === toReplace + "") {

      if (!mongooseUpdateObject) mongooseUpdateObject = {};
      mongooseUpdateObject[path] = replacement;

    } else if (typeof anyType === "object" && anyType !== null && !Array.isArray(anyType)) {

      const keys = Object.keys(anyType);

      for (let i = 0; i < keys.length; i += 1) {

        checkForSearchKey(anyType[keys[i]], `${path}${path !== "" ? "." : ""}${keys[i]}`, keys[i]);
      }

    } else if (Array.isArray(anyType)) {

      for (let i = 0; i < anyType.length; i += 1) {

        checkForSearchKey(anyType[i], `${path}${path !== "" ? "." : ""}${i}`, i);
      }
    }

  }

  checkForSearchKey(document, "", "");

  if (mongooseUpdateObject) {
    console.log(`update object for ${document._id}`, mongooseUpdateObject);
  }

  return mongooseUpdateObject;

}

async function replaceReferencesInCollection(model) {

  const allDocuments = await model.find().lean().exec();

  const replacementPromises = [];

  for (let j = 0; j < allDocuments.length; j += 1) {

    const update = replaceReferencesInDoc(allDocuments[j]);

    if (update) {
      replacementPromises.push(
        model.update({ _id: allDocuments[j]._id }, update).exec(),
      );
    }
  }

  await Promise.all(replacementPromises);

}

async function runReplaceDocument(toReplaceParam, replacementParam, searchParam, arrayOfModels) {
  try {

    toReplace = toReplaceParam;
    replacement = replacementParam;
    searchKey = searchParam;

    const start = new Date().getTime();

    console.log(`searching for ${searchKey} = ${toReplace} to replace with ${replacement}`);
    console.log(" ");
    for (let i = 0; i < arrayOfModels.length; i += 1) {
      console.log(`--- checking collection ${arrayOfModels[i].collection.collectionName} ---`);
      await replaceReferencesInCollection(arrayOfModels[i]); //eslint-disable-line
      console.log(" ");
    }

    console.log(`replace took ${(new Date().getTime() - start) / 1000} seconds`);

  } catch (err) {
    console.log(err);
  }
}
Related Posts Related Posts :
  • React | Can´t load Images > Module not found
  • Dynamically creating buttons in DOJO
  • 404 Not Found in AJAX post call
  • How do I find out, using javascript, what software opened and running my application?
  • Javascript to check the status of wireless connection
  • StarDict support for JavaScript and a Firefox OS App
  • Phonegap event Resume
  • call javascript function on ENTER key press?
  • When is the best time to remove no-js classes from the html tag
  • Recommended email sending languages
  • setInterval not working properly with chrome
  • Does IE create new scope for each script tag?
  • Uncaught SyntaxError: Unexpected token < Underscore and parse issues
  • How to pass captured URL to Email Body in HTML
  • How to structure default nested resources?
  • Store all the keys of a JSON object in a variable
  • Need an efficient way to group the Array of object in javascript
  • a sensible approach to highcharts x-axis labels
  • IDE autocompletion for javascript AMD loading style
  • Bootstrap menu disappears after first click setting the ul style to none
  • split ajax json response errors in each field
  • how to add javascript in head in cmsms
  • REGEX: Finding the correct occurrence order of some given special characters in a string
  • How do you preserve a JavaScript date's time zone from browser to server, and back?
  • Return binary result from phantomjs webserver
  • must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension.
  • Replacing a substring of an element's text with another string
  • How do I filter marks greater than or equal to 90 in this array?
  • Modify the text of my radio input button?
  • Clicking on status bar does not scroll to top of app (Trigger.io)
  • Mocha JS: How to highlight specific assertion failure?
  • $.getJSON jquery parsing to HTML
  • Find items of a certain class (a) that are also in other classes (b,c,d)
  • Setting different images for D3 force-directed layout nodes
  • Integrating Dropzone.js with angular
  • Control sprite animation speed
  • Can only one error / success function be assigned for AngularJS $http promises?
  • Working with math in javascript
  • Django variable isnt recognized by javascript
  • $.when does not work with $.scrollTo plugin
  • How to read local xml file using $.ajax?
  • Manifest is not Valid JSON. What is wrong?
  • AngularJS re-initialise JS after statechange
  • WebRupee is not working
  • How can I make the jQuery MultiSelect widget read-only?
  • How to associate javascript code with dom elements?
  • How to remove track from MediaStream and "stop" webcam?
  • clearvalidators not working in angular 6 form control
  • Remove Count Attribute in json data
  • queue up function callbacks
  • How to stop all Soundcloud streams in once?
  • Sliding div onclick left/right
  • RequireJS JQuery shim doesnt work with VS2013
  • What is the Meteor concurrency model?
  • Events on children of contenteditable element
  • Simple jquery not working to print the input value
  • Javascript templating language in reverse
  • Making Pagination in Javascript Scalable (for large # of db results)
  • Performance of Stateless Authentication in SPA and SSO (Single Sign On)
  • Assigning a value for view asynchronously
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org