How do i design a json result in mongoose? - node.js

My goal is really simple, I want to design this particular json result into mongoose data structure.
Json example
{
"question": "Who was the 13th president of the United States?",
"choice_1": "Millard Fillmore",
"choice_2": "Zachary Taylor",
"choice_3": "Franklin Pierce",
"choice_4" :"James K. Polk",
"answer" :"choice_1"
},
My goal is to transform this json design into mongoose design, and my attempt so far.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const QuestionSchema = new Schema({
question: String,
choice_1: String,
choice_2: String,
choice_3: String,
choice_4: String,
answer: String
});
So later on, during the creation of the question, how do I assign one of the choices to the answer attribute?
const Question = require('/question');
const question = new Question();
question.question = req.body.question;
question.choice_1 = req.body.choice_1;
question.choice_2 = req.body.choice_2;
question.choice_3 = req.body.choice_3;
question.choice_4 = req.body.choice_4;
question.answer = // how do i put choice 1 - 3 here?

Your example refers to the answer by its property name, so:
question.answer = 'choice_3';
Later on, after running a query to retrieve a question, you can use the value of .answer to convert it back to the actual text (for display purposes):
let answer = question[question.answer];

Related

Mongoose - Defining a model for a preexisting collection

I have imported some CSV data to my database through mongoimport, which created my collection during the import.
When defining my model in Node, what do I pass for the schema parameter? Viewing my db in compass shows a schema already created based off the imported data.
I'm currently passing an empty schema which seems totally wrong.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Units = new Schema({
});
module.exports = mongoose.model('Units', Units, 'units');
The schema should contain something like this that defines the kind of data you're working with.
var Units = new Schema({
f_name: String,
l_name: String,
manager: Boolean
});
See 'Defining your schema'.
Also, I don't believe mongoose.model takes a third parameter.
module.exports = mongoose.model('Units',Units);
Edit: yes it does.

Check stored value using mongoose

I’m looking for the fastest way to get all objectIDs of a collection with a privacy value 'public'.
In this image, privacy's value is 'public', so node should give me the '_id' of this object (in this example '57bc4b9f466fab7c099a3f94').
My attempt:
var mongoose = require('mongoose');
mongoose.connect('localhost:27017/databasename');
var Schema = mongoose.Schema;
var collectionsNameSchema = new Schema({
updated: {type: Date },
privacy: { type: Object }
}, {collection: 'spots'});
var collectionsNameData = mongoose.model('collectionsNameData', collectionsNameSchema);
...
collectionsNameData.find({privacy: 'public'})
From what i see you have a problem in query to mongoDB.
Try like this.
collectionsNameData.find({'privacy.value': 'public'});
This should return desired result.
You also may want to use projection as second parameter in find to return only fields that you want. Keep in mind that _id returned by default.
Hope this helps.

Building an api with several arrays which can be updated

I'm new to noSQL and i'm trying to figure out how to create the best possible model structure. What i need to do is every hour to retrieve leagues and matches from an api and add it to my database. Every hour the score might change and new matches might be added to each league and therefor this should be possible in the model. i've read the documentation and created following, however i'm not sure it is possible to update each and add new matches to leagues. What is the ideal modelling for such?
Tournament model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var League = require('./league');
var TournamentSchema = new Schema({
slug: String,
tournaments: [League]
});
module.exports = mongoose.model('Tournament', TournamentSchema);
League
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Match = require('./match');
var leagueSchema = new Schema({
leaguetId: Number,
name: String,
matches: [Match]
});
module.exports = mongoose.model('League', leagueSchema);
Match
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var matchSchema = new Schema({
homeTeam: String,
awayTeam: String,
homeScore: Number,
awayScore: Number,
start: Date
});
module.exports = mongoose.model('Match', matchSchema);
Post request so far
router.post('/tournaments', function(req, res, next) {
var tournament = new Tournament(); // create a new instance of the Bear model
tournament.name = req.body.slug; // set the bears name (comes from the request)
// save the bear and check for errors
tournament.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Tournament created!' });
});
});
If you're adding new matches to leagues and updating matches on a timed interval, why nest them within each other? Lets say you have a match with id 5 whose score changed. In order to find it to update it you'd have to first go through each league, and then iterate through each match in each league until you find the match with id 5. Unless I'm mistaken and there's some easier way to do it, this seems very inefficient.
Why not have two collections? A league collection and a match collection. There will be a 1 (league) : many (match) relationship. When you need to update a match's score, who cares what league it's in? Search the match collection for id 5, and update it.
What would a new match look like? Lets say a league with id 7 had a new match. Add a match to the match collection that has a league id of 7.
If you're really opposed to moving away from one collection.. at least store your matches in an object instead of an array, that way you can find matches with an O(1) lookup time by using it's match name. Instead of O(n) or O(n^2) lookup time like you currently have.

Forming mongo query from String

I am using mongo-parse to parse the mongo queries. Below is my code
var parser = require('mongo-parse')
var queryObject = parser.parse({"city":"Paris"})
//Getting field and value separately
//Field = city
//Value = Paris
var string = 'db.employee.find({"city":"Paris"},{"emp_id":1}'
//Not able to get the field and value separately from string
Is there any node module to generate the mongo query from the above string.
Any help on this will be really helpful
it doesn't look like mongo-parse returns any information about the collection. considering this, couldn't you just take the analysis you get from the parser and hand-construct the query from the data (assuming i'm understanding your question correctly)
e.g.
var newQuery = {};
newQuery[queryObject.field] = queryObject.value;
db.employee.find(newQuery, {emp_id: 1});

Mongoose use dot notation when fields aren't in schema

I have a schema of Dog with strict set to false, allowing for values not in the schema to be saved. However, I can't seem to use dot notation to set values like so:
var dog = new Dog();
dog.name = "Barry"; // works because name is in schema
dog.notInSchema = "This should work!" // doesn't work because its not in the schema
dog.save(...)
Something like this does work:
var dog = new Dog({name : "kyle", notInSChema : "This works and saves" })
dog.save(...)
I need to use dot notation here with fields that aren't in the schema, how can I do this?
The best way to set items on a Mongoose model is with Model#set. In your example, this would be:
var dog = new Dog();
Dog.set('name', 'Barry');
Dog.set('notInSchema', 'this does work');
dog.save(callback);
See http://mongoosejs.com/docs/api.html#document_Document-set

Resources