Create hashid based on mongodb '_id` attribute - node.js

I have my mongo db schema as follows:
var MyTable = mongoose.model('items', {
name: String,
keyId: String
});
I would like to store keyId as a hashid of '_id' for the item being created.
Eg.
Say, i add an item to db "Hello world", and mongodb would create some '_id' for the item while inserting.
I would like to make use of the _id so that i could use that and generate a hashid for the same item being inserted. Something like this:
var Hashids = require("hashids"),
hashids = new Hashids("this is my salt");
var id = hashids.encrypt("507f191e810c19729de860ea");
Is there a way, I could know the id before hand. Or I could let mongodb generate value for my id field based on criteria I specify.

You can use pre save middleware to perform operations on the object instance before it gets saved.
var MyTableSchema = new mongoose.Schema({
name: String,
keyId: String
});
var Hashids = require("hashids");
MyTableSchema.pre('save', function(next) {
if (!this.keyId)
this.keyId = new Hashids("this is my salt").encrypt("507f191e810c19729de860ea");
next();
});
var MyTable = mongoose.model('items', MyTableSchema);

Just a note on this. The Hashids module has an EncryptHex (or EncodeHex in v1.x), that is intended for use with mongodb ids.

Related

How To Return Last Insert ID From NodeJS Sequelize .save() Method

Given this example,
// insert the conversation into the lookup
const LOOKUP = new PrivateMessageLookup;
LOOKUP.communicator1 = communicator1;
LOOKUP.communicator2 = communicator2;
LOOKUP.save();
Where PrivateMessageLookup is the Model
The LOOKUP.save() inserts the record correctly, but how can I get the insert ID of that record?
I can not find an answer.
When you use the Model.create() function it will return a Model Instance that has the ID set. This is a short cut for building a new object, specifying that it is a new record, and then saving it.
// create a new instance from the model
const lookup = await Lookup.create({ communicator1, communicator2 });
// the ID will populate
console.log(lookup.id);
Longhand version:
// build the record, specify it is new
const lookup = Lookup.build({ communicator1, communicator2 }, { isNewRecord: true });
// save
await lookup.save();
// the ID will populate
console.log(lookup.id);

Insert multiple document with mongoose

I made an API with express.js, and i use mongoDB for my database and mongoose as my ODM
I really confused when i want to insert multiple document to my collection in once post request.
Here my model :
const modul = require('../config/require');
const Schema = modul.mongoose.Schema;
let TeleponSchema = new Schema({
_pelanggan : {type: String},
telepon: {type: String, required: true}
});
module.exports = modul.mongoose.model('telepon', TeleponSchema, 'telepon');
and here my controller
const Telepon = require('../models/telepon.model')
exports.create = (req,res) => {
let telepon = new Telepon({
_pelanggan : req.body.pel,
telepon: req.body.telepon
});
telepon.save((err,data) => {
if(err){
res.send({message:'eror', detail: err});
}else{
res.send({message:'success', data: data})
}
});
}
Then i post my request with postman like this :
but the result in my document is :
that's the problem, the value of 'telepon' is in the same row and separated by comma instead of insert a new row and create a new _id
i want the result of my collection like this :
(example)
Any help and suggestion would be much appreciated
Thank you!
1) Per .save call you will only affect one document, check out insertMany to do multiple.
2) req.body.telepon is either an array of numbers, or is already just the comma delimited list of numbers; if it is an array the .toString will result in a comma delimited list anyways. So when you new up the Telepon it has both values in one property, which is what you see in the result.

How to create collection with documents dynamically in mongoose?

I have data of array of objects i.e,
$arrayObj=[{name:'Jack'},{name:'Ram'},{name:'Sham'}];
Now, i need to create collection dynamically with 'mycollection' collection name. After that collection should like be:-
mycollection=> {name:Jack}, {name:Ram}, {name:Sham}
I know how to insert data by using Model.
Got a solution:
var thingSchema = new Schema({}, { strict: false, collection: 'mycollection' });
//strict, if true then values passed to our model constructor that were not specified in our schema do not get saved to the db.
//collection, for prevent from auto append 's'.
var Thing = mongoose.model('mycollection', thingSchema);
var thing = new Thing($arrayObj);
thing.save();

find id of latest subdocument inserted in mongoose

i have a model schema as :
var A = new Schema ({
a: String,
b : [ { ba: Integer, bb: String } ]
}, { collection: 'a' } );
then
var M = mongoose.model("a", A);
var saveid = null;
var m = new M({a:"Hello"});
m.save(function(err,model){
saveid = model.id;
}); // say m get the id as "1"
then
m['b'].push({ba:235,bb:"World"});
m.save(function(err,model){
console.log(model.id); //this will print 1, that is the id of the main Document only.
//here i want to find the id of the subdocument i have just created by push
});
So my question is how to find the id of the subdocument just pushed in one field of the model.
I've been looking for this answer as well, and I'm not sure that I like accessing the last document of the array. I do have an alternative solution, however. The method m['b'].push will return an integer, 1 or 0 - I'm assuming that is based off the success of the push (in terms of validation). However, in order to get access to the subdocument, and particularly the _id of the subdocument - you should use the create method first, then push.
The code is as follows:
var subdoc = m['b'].create({ ba: 234, bb: "World" });
m['b'].push(subdoc);
console.log(subdoc._id);
m.save(function(err, model) { console.log(arguments); });
What is happening is that when you pass in the object to either the push or the create method, the Schema cast occurs immediately (including things like validation and type casting) - this means that this is the time that the ObjectId is created; not when the model is saved back to Mongo. In fact, mongo does not automatically assign _id values to subdocuments this is a mongoose feature. Mongoose create is documented here: create docs
You should also note therefore, that even though you have a subdocument _id - it is not yet in Mongo until you save it, so be weary of any DOCRef action that you might take.
The question is "a bit" old, but what I do in this kind of situation is generate the subdocument's id before inserting it.
var subDocument = {
_id: mongoose.Types.ObjectId(),
ba:235,
bb:"World"
};
m['b'].push(subDocument);
m.save(function(err,model){
// I already know the id!
console.log(subDocument._id);
});
This way, even if there are other database operations between the save and the callback, it won't affect the id already created.
Mongoose will automatically create an _id for each new sub document, but - as far as I know - doesn't return this when you save it.
So you need to get it manually. The save method will return the saved document, including the subdocs. As you're using push you know it will be the last item in the array, so you can access it from there.
Something like this should do the trick.
m['b'].push({ba:235,bb:"World"});
m.save(function(err,model){
// model.b is the array of sub documents
console.log(model.b[model.b.length-1].id);
});
If you have a separate schema for your subdocument, then you can create the new subdocument from a model before you push it on to your parent document and it will have an ID:
var bSchema = new mongoose.Schema({
ba: Integer,
bb: String
};
var a = new mongoose.Schema({
a: String,
b : [ bSchema ]
});
var bModel = mongoose.model('b', bSchema);
var subdoc = new bModel({
ba: 5,
bb: "hello"
});
console.log(subdoc._id); // Voila!
Later you can add it to your parent document:
m['b'].push(subdoc)
m.save(...

Mongoose embedded documents / DocumentsArrays id

In the Mongoose documentation at the following address:
http://mongoosejs.com/docs/embedded-documents.html
There is a statement:
DocumentArrays have an special method id that filters your embedded
documents by their _id property (each embedded document gets one):
Consider the following snippet:
post.comments.id(my_id).remove();
post.save(function (err) {
// embedded comment with id `my_id` removed!
});
I've looked at the data and there are no _ids for the embedded documents as would appear to be confirmed by this post:
How to return the last push() embedded document
My question is:
Is the documentation correct? If so then how do I find out what 'my_id' is (in the example) to do a '.id(my_id)' in the first place?
If the documentation is incorrect is it safe to use the index as an id within the document array or should I generate a unique Id manually (as per the mentioned post).
Instead of doing push() with a json object like this (the way the mongoose docs suggest):
// create a comment
post.comments.push({ title: 'My comment' });
You should create an actual instance of your embedded object and push() that instead. Then you can grab the _id field from it directly, because mongoose sets it when the object is instantiated. Here's a full example:
var mongoose = require('mongoose')
var Schema = mongoose.Schema
var ObjectId = Schema.ObjectId
mongoose.connect('mongodb://localhost/testjs');
var Comment = new Schema({
title : String
, body : String
, date : Date
});
var BlogPost = new Schema({
author : ObjectId
, title : String
, body : String
, date : Date
, comments : [Comment]
, meta : {
votes : Number
, favs : Number
}
});
mongoose.model('Comment', Comment);
mongoose.model('BlogPost', BlogPost);
var BlogPost = mongoose.model('BlogPost');
var CommentModel = mongoose.model('Comment')
var post = new BlogPost();
// create a comment
var mycomment = new CommentModel();
mycomment.title = "blah"
console.log(mycomment._id) // <<<< This is what you're looking for
post.comments.push(mycomment);
post.save(function (err) {
if (!err) console.log('Success!');
})

Resources