MongoDB javascript ingest JSON string - javascript

I have a big JSON string that is 10 records, each with their own properties. I need to ingest them into my MongoDB with Javascript. I'm basically useless with Javascript, and google has largely failed me. The JSON looks like this, basically:
[{"ID":1,"Name":"bob"},{"ID":2,"Name":"Jim"}]
Obviously a lot more, but that's the basic structure. How would one, using Node.js for example, import that into Mongo? Mongo's documentation largely only covers their shell commands, but those dont' directly translate into Javascript.

You could do a bulk insert like so:
var MyObject = mongoose.model('MyObject', MyObjectSchema);
var objectsArray = [/* array of MyObject objects */];
MyObject.collection.insert(objectsArray, callback);

Well i normally use mongoose plugin driver, to save such a document , define the schema first, at a glance your schema seems to have two fields ID and Name, with id custom. It is custom because mongodb uses it own id, to change this use auto-increment-plugin. So after you define your schema, mongodb will only save or insert a object if the fields match the schema.
db.collection.insert(
<document or array of documents>,
{
writeConcern: <document>,
ordered: <boolean>
}
)
The above is the format for a document insertion.document document or array A document or array of documents to insert into the collection.
Hope this helps.

Related

Using findOne with Arrays in Mongoose with NodeJS

in NodeJS with Mongoose, how do i search something in an array using findOne()? I want to search stuff like 626ead978edc5f2a3f7ca924 in the users array in my sessionCollection-Model.
My DB looks like this: Database Picture
It'll work normally as it does for non array key:
SessionCollection.findOne({users: mongoose.Types.ObjectId("626ead978edc5f2a3f7ca924")})
You might need to cast to objectId to get the desired result.
Reference

How to get content from all nested/linked documents in single query to Prismic?

I know that it's possible to pass the config object as the second parameter and defined which fields I need but it's really inconvenient because I have a lot of them:
client.query(
Prismic.Predicates.at('document.type', 'my_page'),
{'fetchLinks': ['section1.title', 'section1.subtitel', 'section2.title', 'section2.image', .......]}
);
Is it possible to get data(content) of all nested fields for linked documents in a single query?
Try using the new GraphQL API: https://prismic.io/docs/rest-api/query-the-api/graphquery
Slightly tedious but works!

Set property in mongoose object after query [duplicate]

This question already has answers here:
Why can't you modify the data returned by a Mongoose Query (ex: findById)
(3 answers)
Closed 3 years ago.
while development of an API, I often need to set extra properties in the result of mongoDb query results. But I can't do it in a good way. For example
Model
const Cat = mongoose.model('Cat', { name: String,age:Number });
Query
Cat.findOne({age:2}) .then(
cat=>{
cat.breed="puppy";
console.log(cat)
} )
here after I get the result from mongoDb I want to set the property of breed to the result , but I can't do it because the property is not defined in the Schema
So to set an extra property I use a hack
cat = JSON.parse(JSON.stringify(cat));
cat.favFood = "Milk"
I don't think its a good way to code. please give a better way of setting property and explain how the hack is working.
Mongoose can actually do the conversion toObject for you with the .lean() option. This is preferred over manual conversion after the query (as willis mentioned) because it optimizes the mongoose query by skipping all the conversion of the raw Mongo document coming from the DB to the Mongoose object, leaving the document as a plain Javascript object. So your query will look something similar to this:
Cat.findOne({age:2}).lean().then(
cat=>{
cat.breed="puppy";
console.log(cat)
}
)
The result will be the same except that this will skip the Mongoose document-to-object conversion middleware. However, note that when you use .lean() you lose all the Mongoose document class methods like .save() or .remove(), so if you need to use any of those after the query, you will need to follow willis answer.
Rather than using JSON.parse and JSON.stringify, you can call toObject to convert cat into a regular javascript object.
Mongoose objects have methods like save and set on them that allow you to easily modify and update the corresponding document in the database. Because of that, they try to disallow adding non-schema properties.
Alternatively, if you are trying to save these values you to the database, you may wish to look into the strict option (which is true by default).

Can I save a JS object (with methods) in MongoDB?

I have some objects that encode text formatting methods and css styles, and I'd like to save them in a MongoDB collection (using Mongoose). The objects are a more complicated version of this:
const myStyle = {
book: {
templates: ["/authors/. ", "/title/. ", "/date/. "],
authors: {
format: formatAuthors
},
title: {
format: formatTitle,
style: {fontStyle: "italic"}
}
}
}
Does anyone know how to send this this sort of thing to a server and save it in a MongoDB collection? According to the Mongoose documentation, Object is not a valid schemaType, so I can't just save it straightforwardly as a JS object.
You can add methods through the Schema.methods field.
SchemaName.methods.methodName = function(){...}
Also take a look at this example here for basic mongoose usage.
Object is not a valid mongoose schema type but Mixed is.
An "anything goes" SchemaType, its flexibility comes at a trade-off of
it being harder to maintain. Mixed is available either through
Schema.Types.Mixed or by passing an empty object literal.
You can read more about it using the above link.
In your case as long as the data you want to save is valid JS object you will be able to insert it.
Please note however that since it is a schema-less type there are some performance limitations when using Mixed as well as you need to call .markModified(path) when changed as again stated in the docs.
No, you can't save methods to mongodb

Firebase - Get All Data That Contains

I have a firebase model where each object looks like this:
done: boolean
|
tags: array
|
text: string
Each object's tag array can contain any number of strings.
How do I obtain all objects with a matching tag? For example, find all objects where the tag contains "email".
Many of the more common search scenarios, such as searching by attribute (as your tag array would contain) will be baked into Firebase as the API continues to expand.
In the mean time, it's certainly possible to grow your own. One approach, based on your question, would be to simply "index" the list of tags with a list of records that match:
/tags/$tag/record_ids...
Then to search for records containing a given tag, you just do a quick query against the tags list:
new Firebase('URL/tags/'+tagName).once('value', function(snap) {
var listOfRecordIds = snap.val();
});
This is a pretty common NoSQL mantra--put more effort into the initial write to make reads easy later. It's also a common denormalization approach (and one most SQL database use internally, on a much more sophisticated level).
Also see the post Frank mentioned as that will help you expand into more advanced search topics.

Categories

Resources