Search code examples
node.jsmongodbmonk

Mongod: inserting entry with customer _id (monk/node.js)


I have read that any _id type can be used except for Array. (But cannot seem to find. Can you guys confirm this please?)

I would like the username (string) to be the _id for performance reasons.

In Node.js:

const monk = require('monk');
const db = monk('localhost:27017/test',
    function(err) {
        if(err)
            console.log(err.toString());
    });
//const doc = {user: 'aa', password: 'password'};
//const doc = {_id: 'aa', password: 'password'};
const doc = {_id: monk.id('aa'), password: 'password'};
var users = db.get('users');
users.insert([doc]);

The first commented line works, but the other lines both error out:

  • _id: monk.id('aa') errors out immediately
  • _id: 'aa' errors out when doing users.insert() because I guess it tries to cast the string into an Id

The error is the same regardless:

Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

How can I use a given string for _id?

ps: to run this code, you need mongo running, mongod --dbpath data, and nodejs: npm install monk; nodejs.


Solution

  • monk.id(ARG) will cast ARG to an ObjectId (documentation), which is not what you want.

    Instead, just pass the string directly:

    const doc = { _id: 'aa', password: 'password' };
    

    Since Monk also casts id's to ObjectId automatically, you have to disable autocasting:

    const db   = monk('localhost:27017/test', ...);
    db.options = { 
      safe    : true,
      castIds : false
    };