(re)Populating mongodb collection from json - mongoose - node.js

Hi is there a way to repopulate a mongo collection from a json array using mongoose?
I have this schema.
var UserNote_Schema = new Schema({
user_id: {type:ObjectId, ref:require('../User/User_Schema.js')},
note: {type:String},
created: {type:Date},
last_mod: {type:Date}
});
and would like to populate it with this json and have it save to the collection.
{"_id":"506b8922a6bd97d322000011",
"user_id":"504aaeef898f541527000012",
"note":"a note","created":"2012-03-10T00:38:58.000Z",
"last_mod":"2012-03-10T00:38:58.000Z"}
My goal is to reset my database to a certain state after running some tests which add remove and change some of the data within.
However, if there is more convenient way of achieving a database reset from a previous state in mongoose/mongo I'd much appreciate any pointers. Keeping the versioning info would also be nice.
thanks

Related

What happens if I delete a Model class (.js) in Node JS

I recently started taking a course on Node JS and Mongo DB. During the course, I created a model class:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const IdeaSchema = new Schema({
title: {
type: String,
required: true
},
details: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
mongoose.model('ideas', IdeaSchema);
This created a 'table' (correct me if I'm wrong) in the MongoDB database, and editing the class changed the design of the table. So, what happens if I delete the class? Does the 'table' get deleted? Why? And if not, how can I delete it?
Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection. It's just a blueprint of the house, deleting the Schema doesn't mean you are deleting the actual physical house or in mongoDB the collection.
You can change your schema anytime, without having any changes / effect on your old documents. You can still retrieve it and add new documents with new added fields based on the new modified schema.
To easily manage your mongoDb data, you can install tools like Robo3T see https://robomongo.org If you are new in mongo, this kind of tools will save you time and help you manage your dbs and collections easily. Everytime you change / add new schemas, you can use the tool to delete db, delete collections, insert documents, etc.
Or if you are just accessing mongo via terminal, this mongo shell commands will help you https://www.opentechguides.com/how-to/article/mongodb/118/mongodb-cheatsheat.html
For more details on mongoose schema, see https://mongoosejs.com/docs/guide.html
your table didn't get deleted. just your schema changed and added your new field in same table.

Should I create New Schema Model file for every route OR use already created Schema?

Suppose I have a User Schema which has around 30 fields, and other 3 schemas also.
UserSchema.js
user_schema = new Schema({
user_id: { type: String},
.........//30 properties
});
ctrs_schema = new Schema({
.........10 properties
});
ids_schema = new Schema({
.........5 properties
});
comments_schema = new Schema({
.........10 properties
});
Now I am writing a route which will change the gender of the user, Now in order to do it I can use UserSchema.js but that will load all of the schemas into my route, whereas if I would have created a new file which had only one schema with two fields, then all schemas will not get loaded into the memory for the route.
UserGenderSchema.js
gender_schema = new Schema({
user_id: { type: String},
gender: { type: String}
});
I know there are pros and cons of both of the ways
Pros -
I have to edit only in single file if I would have to change something
for any field.
Cons -
All Schemas are Loading for all routes which are unnecesary. Memory
Wastage.
Will, there be any less memory usage between both of the ways on the threads?
Can anyone Please tell me which architecture will be better or what you are implementing in your project and why?
Thanks
It's better to keep user related fields in just one schema, cause mongo has been there because of its non-relational structure and it gained its performance by keeping relational structures away, so if you create a schema for each field and then create a reference in each of them to point out to the user they are related to, you are kind of using mongo to build a heavily relational structure and mongo is not good as it should be in this situation, so if later on your application you want to somehow show all the information of the user or try to update multiple fields of user or try to show more information of the user in one of your routes or something, you will end up having some serious performance issues. as a conclusion, the cost of loading all the schema to touch only one field is not as much as the cost of breaking down your data structure.

mongoose .save() ignores ObjectId _id

I have a mongoose schema collection A. Then, I create a new object as follows
var myA = new A({
name: 'A simple name'
});
As long as I know, once we have done this, a new _id attribute is created for that object. This means that at the end of the day, myA should look (and it actually looks) like
{
name: 'A simple name',
_id: ObjectId
}
the problem is that when I hit
myA.save()
it is saved into mongodb with a different _id than the previously created.
An idea on why this could be happening? I'm using mongoose 4.4.8
I guess when you create a new document with new A({... it internally marks itself as new document which is evaluated later when calling save() to generate an appropriate MongoDB statement - and this 'flag' is probably not updated immediately when calling save(). This has the positive side effect of having the possibility to quickly create clones of documents when you want to generate test data :)
If you want to update your newly saved document right after creation then you should do that in the callback of the save method which gets the saved document in its 2nd parameter.

Is it possible to set read preference at the collection level?

I have a large collection of metadata, and I'd like to know if there's a way to set a secondaryPreferred read preference once, for the whole collection, rather than setting it repeatedly at the query level all over the application code.
Is this possible? Currently using mongoose 3.6.x.
I figured this out myself - it can be set in the schema options.
Example:
var MySchema = new Schema({
thing: String,
count: Number
}, {read: 'secondaryPreferred'});

How do I get Mongoose to find none Mongoose created data within MongoDB?

Can someone please stop me from going insane!
I have a MongoDB database which has a simply database that was created and populated via Mongoose, this works great I can perform finds woth no problems at all.
I went into the Mongo console and created a new database with just use newDB and the performed a simple insert, I inserted several records and they appeared fine within Mongo. I can find on them and so all the Mongo operations but when I try to perform a find on this database Mongoose returns a null???
I have noticed that the database I created in Mongo console does not create the '__v' field which I believe is for Mongoose internal indexing uses, I have created this field in my custom tables but still no joy I just cannot create data from outside of Mongoose and use it within my app??????
I have spent hours looking into this and reading maybe I just missed something but honestly I cannot find a thing on this and many people must hit this every week????
**Sorry here is the code I am running against the database:
exports.adduser = function(req, res){
var mongoose = require("mongoose");
mongoose.connect("localhost/nm", function(err){
if(err)throw(err);
console.log("Connected to MongoDB successfully...")
var schema = mongoose.Schema({
Firstname: String,
Lastname: String,
MiddleInitial: String,
Password: String,
Username: String
});
var auser = mongoose.model("Users", schema);
auser.find({}, function(err, alist){
console.log(">>>>"+alist);
});
});
**
Thanks again!!!!! for your input it is very much appreciated....
try inspecting mongo instance with
show dbs
use <dbName>
in mongo shell to make sure you are using the right database and then
show collections
or alternatively
db.getCollectionNames()
To see if your collections are there or not.
__v is a document version property incremented only for array operations(mongoose 3).
Your connection string might be wrong.
Anyone experiencing this problem and I know there are a good few read the comment by robertklep above it solved my problems very quickly!
DOnt know how the accept a comment sorry!

Resources