Ricardo Cruz Ricardo Cruz - 1 year ago 211
Node.js Question

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

I have read that any

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
for performance reasons.

In Node.js:

const monk = require('monk');
const db = monk('localhost:27017/test',
function(err) {
//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');

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
    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

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

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download