How to create collection with documents dynamically in mongoose? - node.js

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();

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

Mongoose find data from dynamic Collection

I am new to MongoDB & working on a MEAN application.
In the mongo database(I am using mongoose), the collections are adding dynamically from third party API like schoolList1,schoolList2,schoolList3,schoolList4,....
I am facing problem to find a solution to get data from collections, Like If a user sends the argument from FrontEnd to find data from schoolList3.
The find function should apply on that collection only & return the data.
I am unable to solve it that how should I get data without passing schema and did not get any other way.
Set collection name option for your schema from user's input:
var collectionName = 'schoolList3'; // set value from the input
var dataSchema = new Schema({/** your schema here **/}, { collection: collectionName });

Mongoose validate Schema with no Model

I want to validate some inner elements of an object against schemas that are members of a larger schema before posting that object on the model correspondent to that larger schema.
Someone already asked this question and this answer has something similar on the second option proposed:
var p = new People({
name: 'you',
age: 3
});
p.validate(function(err) {
if (err)
console.log(err);
else
console.log('pass validate');
});
The problem is that before doing the validation one has to create a new model with var People = mongoose.model('People', peopleSchema);.
Does this mean in this case that a new collection 'People' will be stored in the MongoDB database?
Is the act of calling mongoose.model('People', peopleSchema); altering the database in any way?
If so, is there a way to do this validation without creating a new collection, in this case 'People'?
The schema I want to validate will be stored as a component of another document already in the database and I don't want to pollute the database with unused collections.

Create hashid based on mongodb '_id` attribute

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.

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

Resources