Mongoose and Postman: test a model with nested objects - node.js

I created a model like this in nodeJS, using Mongoose:
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var plantSchema = new Schema({
plantData: [
{
family: { type: String, default: 'Liliaceae' },
genusObj: {
genus: { type: String, required: 'Please enter the genus plant name' },
tulipGroup: { type: String }, // e.g. Single Early
tulipGroupNumber: { type: Number } // e.g. 1
},
species: { type: String, required: 'Please enter the species plant name' },
commonName: { type: String },
description: { type: String },
mainImage: {},
otherImages: {},
images: {},
}
],
detailsData: [ .... ]
});
module.exports = mongoose.model('plants', plantSchema);
And this is my controller:
var mongoose = require('mongoose'),
Plant = mongoose.model('plants');
// READ ALL
exports.list_all_plants = function(req, res) {
Plant.find({}, function(err, plants) {
if (err) {
res.send(err);
}
res.json(plants);
});
};
// CREATE
exports.create_new_plant = function(req, res) {
var new_plant = new Plant(req.body);
new_plant.save(function(err, plant_inserted) {
if (err) {
res.send(err);
}
res.json(plant_inserted);
});
};
// READ (probably plantId comes from an _id previously retrieved)
exports.read_a_plant = function(req, res) {
Plant.findById(req.params.plantId, function(err, plant_searched) {
if (err) {
res.send(err);
}
res.json(plant_searched);
});
};
// UPDATE
exports.update_a_plant = function(req, res) {
Plant.findOneAndUpdate(
{
_id: req.params.plantId
},
req.body,
{new: true},
function(err, plant_to_update) {
if (err) {
res.send(err);
}
res.json(plant_to_update);
}
);
};
// DELETE
exports.delete_a_plant = function(req, res) {
Task.remove(
{
_id: req.params.plantId
},
function(err, task) {
if (err) {
res.send(err);
}
res.json({ message: 'Plant successfully deleted' });
}
);
};
And finally, i have this router:
'use strict';
module.exports = function(app) {
var plantList = require('../controllers/plantController');
// plant routes
app.route('/plants')
.get(plantList.list_all_plants)
.post(plantList.create_new_plant);
app.route('/plants/:plantId')
.get(plantList.read_a_plant)
.put(plantList.update_a_plant)
.delete(plantList.delete_a_plant);
What I'd like to do is testing all this with Postman.
If I try with the GET method, using simply
http://localhost:3000/plants
everything works fine: I mean, it returns an empty array (mongodb is up and running, and everything is set).
Now I wanted to try to insert a new element with Postman: I selected POST and x-www-form-urlencoded under body. Required properties are plantData{genusObj{genus}} and plantData{species} : since I'm quite new with both postman and mongodb, how can I enter a sub-element in postman, to create a new Plant ?
there are only KEY and VALUE options, and i don't know how to write a sub-key like plantData->genusObj->genus.
P.S.: Suggestions on data model are welcome, I tried to build a generic plant database but oriented on tulips (so usually i can enter tulips, but if i need to enter something else, i can).

Well, it seems that this answer fits to me: in fact, on Postman i selected under "body" the "raw" option, then I selected JSON instead of TEXT from the dropdown menu, and finally I used this object (meanwhile I slightly changed the
model) - don't forget the " symbols everywhere, like I did - ' is not accepted:
{
"plantData": [
{
"family": "Liliaceae",
"genusObj": {
"genus": "Tulipa",
"tulipGroup": "Single Late",
"tulipGroupNumber": 5
},
"species": "TEST",
"sellName": "Queen of night",
"description": "black tulip",
"mainImage": "",
"otherImages": "",
"images": ""
}
],
"sellingData": [
{
"price": 0.50,
"availableQuantity": 100
}
],
"detailsData": [
{
"heightInCm": "60-65",
"floweringTime": "late spring",
"plantDepthCm": "20",
"plantSpacingCm": "10",
"bulbSizeInCm": "12",
"flowerColor": "Black",
"lightRequirements": "full sun"
}
]
}

Related

mongoose delete from array

I need to remove the user's id from all objects in the collection except the one that was passed, in my example it is value: 'Тата', tell me how to make such a request?
console.log(result)
[
{
_id: 5fa702b2f18e5723b4c00d9f,
value: 'Тата',
vote: { '36e7da32-f818-4771-bb5e-1807b2954b5f': [Array] },
date: 2020-11-07T20:25:22.611Z,
__v: 0
}
]
console.log(req.body)
{ value: 'Тата', habalkaId: '36e7da32-f818-4771-bb5e-1807b2954b5f' }
console.log(req.user._id)
5f63a251f17f1f38bc92bdab
that's all I could do, just find
router.post('/', passport.authenticate('jwt', {session: false}), (req, res) => {
FirstName.find({value: req.body.value})
.then(result => {
if (result.length) {
console.log(result)
console.log(req.body)
console.log(req.user._id)
FirstName.find({value: {$ne: 'Слоник'}}, function (err, arr) {
arr.map(e => {
if (e.vote[req.body.habalkaId].length) {
if(e.vote[req.body.habalkaId].includes(String(req.user._id))){
console.log(e.vote[req.body.habalkaId])
}
}
})
})
} else {
new FirstName({
value: req.body.value,
vote: {[req.body.habalkaId]: [String(req.user._id)]}
}).save();
}
})
// res.json({res: req.body})
})
FirstName.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const FirstNameSchema = new Schema({
value: {
type: String
},
vote: {
type: Object
},
date: {
type: Date,
default: Date.now
}
});
module.exports = FirstName = mongoose.model('firstname', FirstNameSchema);
If I've understand well, you want something like this:
db.collection.update({
"value": {
"$ne": "tata"
}
},
{
"$pull": {
"vote.array_name": "id_value"
}
},
{
multi: true
})
First of all, find all document that not match the value with the given one. Then, for each document found, delete the object from the array, using $pull where the id given matches.
Example here
Please check the payground and check if I've used the correct schema and it shows the expected output.

Cannot find id and update and increment sub-document - returns null Mongoose/mongoDB

I have a problem where I cannot seem to retrieve the _id of my nested objects in my array. Specifically the foods part of my object array. I want to find the _id, of lets say risotto, and then increment the orders count dynamically (from that same object).
I'm trying to get this done dynamically as I have tried the Risotto id in the req.body._id and thats fine but i can't go forward and try to increment orders as i get null.
I keep getting null for some reason and I think its a nested document but im not sure. heres my route file and schema too.
router.patch("/update", [auth], async (req, res) => {
const orderPlus = await MenuSchema.findByIdAndUpdate({ _id: '5e3b75f2a3d43821a0fb57f0' }, { $inc: { "food.0.orders": 1 }}, {new: true} );
//want to increment orders dynamically once id is found
//not sure how as its in its own seperate index in an array object
try {
res.status(200).send(orderPlus);
} catch (err) {
res.status(500).send(err);
}
});
Schema:
const FoodSchema = new Schema({
foodname: String,
orders: Number,
});
const MenuSchema = new Schema({
menuname: String,
menu_register: Number,
foods: [FoodSchema]
});
Heres the returned Database JSON
{
"_id": "5e3b75f2a3d43821a0fb57ee",
"menuname": "main course",
"menu_register": 49,
"foods": [
{
"_id": "5e3b75f2a3d43821a0fb57f0",
"foodname": "Risotto",
"orders": 37
},
{
"_id": "5e3b75f2a3d43821a0fb57ef",
"foodname": "Tiramisu",
"orders": 11
}
],
"__v": 0
}
the id for the menuname works in its place but i dont need that as i need to access the foods subdocs. thanks in advance.
You are sending food id (5e3b75f2a3d43821a0fb57f0) to the MenuSchema.findByIdAndUpdate update query. It should be the menu id which is 5e3b75f2a3d43821a0fb57ee
You can find a menu by it's id, and update it's one of the foods by using food _id or foodname using mongodb $ positional operator.
Update by giving menu id and food id:
router.patch("/update", [auth], async (req, res) => {
try {
const orderPlus = await MenuSchema.findByIdAndUpdate(
"5e3b75f2a3d43821a0fb57ee",
{ $inc: { "foods.$[inner].orders": 1 } },
{ arrayFilters: [{ "inner._id": "5e3b75f2a3d43821a0fb57f0" }], new: true }
);
res.status(200).send(orderPlus);
} catch (err) {
res.status(500).send(err);
}
});
Update by giving menu id and foodname:
router.patch("/update", [auth], async (req, res) => {
try {
const orderPlus = await MenuSchema.findByIdAndUpdate(
"5e3b75f2a3d43821a0fb57ee",
{ $inc: { "foods.$[inner].orders": 1 } },
{ arrayFilters: [{ "inner.foodname": "Risotto" }], new: true }
);
res.status(200).send(orderPlus);
} catch (err) {
res.status(500).send(err);
}
});

How two select two column value as key value pair in mongoose using expressjs

i have the schema is like below
Resource.js
var mongoose = require("mongoose"),
Schema = mongoose.Schema,
objectId = mongoose.Schema.ObjectId;
var lableShema = new Schema({
labelName: { type: String },
language: { type: String, },
resourceKey: { type: String, },
resourceValue: { type: String, }
}, {
versionKey: false
});
var lableShema = mongoose.model('LabelKeyResource', lableShema);
module.exports = lableShema;
in db i have the data like this,
{
"_id": "59b1270b4bb15e1358e47cbd",
"labelName": "submit",
"__v": 0,
"resourceKey": "submit_btn",
"resourceValue": "Submit",
"language": "engilish"
}
i'm using the select function is
lableResource.find({ language: req.params.ln}, function (err, data) {
if (err) {
res.send(err);
return;
}
res.send(data);
but i want this format how to that...
{"submit_btn":"Submit","select_lbl":"Please Select"}
You can format the data after getting the data from Mongo.
This is how you can do it:
var obj = {
[data.resourceKey]: data.resourceValue,
select_label: "Please Select"
};
This will give you the object: {"submit_btn":"Submit","select_lbl":"Please Select"}

elasticsearch search text return full array issue

I am using mongoosastic for elasticsearch. and i done all setup and its working fine. but problem is result are not getting properly.
FILE:- mongoose and mongoosastic.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var medicineSchema = require('./search')
var mongoosastic = require("mongoosastic");
var UserProfileSchema = new Schema({
userId: String,
username: String,
address: String,
number: Number,
task: [{
name: {
type: String,
es_boost: 2.0 // or es_indexed:true
},
taskCode: String,
}]
});
UserProfileSchema.plugin(mongoosastic);
UserProfileSchema.plugin(mongoosastic, {
host: "localhost",
port: 9200,
// ,curlDebug: true
});
UserProfile = module.exports = mongoose.model('UserProfile', UserProfileSchema);
UserProfile.createMapping(function(err, mapping) {
if (err) {
console.log('error creating mapping (you can safely ignore this)');
console.log(err);
} else {
console.log('mapping created!');
console.log(mapping);
}
});
And my search Query:
var UserProfileSchema = require('../../app/models/user');
UserProfileSchema.search({
query_string: {
query: name
}
}, function(err, result) {
if (err) {
callback({
RESULT_CODE: '-1',
MESSAGE: 'System error'
});
} else {
callback({
RESULT_CODE: '1',
DATA: result
});
}
});
Now my problem is if task array has 3 object and when i search for task string i.e "abc" it will return full collection. with all task But i want only searched string object from task array. i.e name :abc object
......
"task" [{
name: 'abc',
taskCode: 123
},{
name: 'xyz',
taskCode: 123
},{
name: 'cdx',
taskCode: 123
}]
The good thing is that your task field is already of type nested in your schema, which is a pre-condition for achieving what you expect.
Now in order to achieve what you want you need to use inner_hits in your query.
UserProfileSchema.search({
"query": {
"nested": {
"path": "task",
"query": {
"match": {
"task.name": name
}
},
"inner_hits": {} <--- this does the magic
}
}
}, ...

Mongoose Insert many to one

I need to help!
I'm creating a website with nodejs and mongo for learning.
I have a problem that I know the best way to do it.
I have two collections codes and tag into table codes I have the tags field is array of tags.
CodeModel:
var CodeSchema = new Schema({
title: { type: 'String', required: true },
text: { type: 'String', required: true },
url: { type: 'String', required: true },
uri: String,
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now },
owner: {
type: Schema.ObjectId,
ref: 'User'
},
tags: [
{
type: Schema.ObjectId,
ref: 'Tag'
}
]
});
CodeSchema.pre("save", function (next) {
// if create for first time
if (!this.created_at) {
this.created_at = Date.now();
}
next();
});
module.exports = mongoose.model('Code', CodeSchema);
And My Tag Model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TagSchema = new Schema({
name: 'string'
});
module.exports = mongoose.model('Tag', TagSchema);
when I get the result in my rest I got it:
[
{
"_id": "5540f557bda6c4c5559ef638",
"owner": {
"_id": "5540bf62ebe5874a1b223166",
"token": "7db8a4e1ba11d8dc04b199faddde6a250eb8a104a651823e7e4cc296a3768be6"
},
"uri": "test-save",
"url": "http://www.google.com.br/",
"text": " hello ",
"title": "testing...",
"__v": 0,
"tags": [
{
"_id": "55411700423d29c70c30a8f8",
"name": "GO"
},
{
"_id": "55411723fe083218869a82d1",
"name": "JAVA"
}
],
"updatedAt": "2015-04-29T15:14:31.579Z",
"createdAt": "2015-04-29T15:14:31.579Z"
}
]
This I populate into database, I don't know how I insert it, is there any way automatic with mongoose that to do it or I need to create by myself?
I am testing with this json:
{
"url": "http://www.google.com.br/",
"title": "Test inset",
"text": "insert code",
"tags": [
"ANGULAR",
{
"_id": "55411700423d29c70c30a8f8",
"name": "GO"
}
]
}
I need to do a insert of tags, if I have id or not. Do I need to create it or has way to do it automatically?
and how can I do it?
Sorry my english =x
Generally speaking to create and save a document in a mongo database using mongooseJS is fairly straightforward (assuming you are connected to a database):
var localDocObj = SomeSchemaModel(OPTIONAL_OBJ); // localDocObj is a mongoose document
localDocObj.save(CALLBACK); // save the local mongoose document to mongo
If you have an object that is of the same form as the schema, you can pass that to the constructor function to seed the mongoose document object with the properties of the object. If the object is not valid you will get an invalidation error passed to the callback function on validate or save.
Given your test object and schemas:
var testObj = {
"url": "http://www.google.com.br/",
"title": "Test inset",
"text": "insert code",
"tags": [
"ANGULAR",
{
"_id": "55411700423d29c70c30a8f8",
"name": "GO"
}
]
};
var codeDoc = Code(testObj);
codeDoc.save(function (err, doc) {
console.log(err); // will show the invalidation error for the tag 'Angular'
});
Since you are storing Tag as a separate collection you will need to fetch/create any tags that are string values before inserting the new Code document. Then you can use the new Tag documents in place of the string values for the Code document. This creates an async flow that you could use Promises (available in newer node releases) to manage.
// Create a promise for all items in the tags array to iterate over
// and resolve for creating a new Code document
var promise = Promise.all(testObj.tags.map(function(tag) {
if (typeof tag === 'object') {
// Assuming it exists in mongo already
return tag;
}
// See if a tag already exists
return Tag.findOne({
name: tag
}).exec().then(function(doc) {
if (doc) { return doc; }
// if no tag exists, create one
return (Tag({
name: tag
})).save(); // returns a promise
});
})).then(function(tags) {
// All tags were checked and fetched/created if not an object
// Update tags array
testObj.tags = tags;
// Finally add Code document
var code = Code(testObj);
return code.save();
}).then(function(code) {
// code is the returned mongo document
console.log(code);
}).catch(function(err) {
// error in one of the promises
console.log(err);
});
You can do it like
var checkNewTagAndSave = function(data, doc, next){ // data = req.body (your input json), doc = mongoose document to be saved, next is the callback
var updateNow = function(toSave, newTags){
// save your mongoose doc and call the callback.
doc.set(toSave);
doc.save(next);
};
var data = req.body;
var tagsToCreate = [];
var tagids = [];
data.tags.forEach(function(tag, index){
if(typeof(tag) == 'string') {
tagsToCreate.push({ name: tag });
} else tagids.push(tag._id);
});
data.tags = tagids;
if(tagsToCreate.length === 0) updateNow(data);
else {
mongoose.model('tag').create(tagsToCreate, function(err, models){
if(err || !models) return next(err);
else {
models.forEach(function(model){
data.tags.push(model._id);
});
updateNow(data, models);
}
});
}
};
Hope code is reflecting its logic itself
usage :
after you have found your Code document say aCode
just call
checkNewTagAndSave(req.body, aCode, function(err, doc){
//end your response as per logic
});

Resources