I created function which is adding people_id inside array of given card. But there is problem that inserted id is always not as an objectId() where I just need it to be saved as objectId.
When id is added to array i I'm sending whole variable board JSON to nodejs API where is executed function findOneAndUpdate. And here is problem because after saved this arrays is not objectID in Author. Can someone tell me how to make it?
JSON board
{
"_id" : ObjectId("59e096a7622a3825ac24f343"),
"name" : "1",
"users" : [
ObjectId("59cd114cea98d9326ca1c421")
],
"lists" : [
{
"list" : "1",
"cards" : [
{
"name" : "2",
"Author" : [
"59df60fb6fad6224f4f9f22d",
"59df60fb6fad6224f4f9f22d",
"59df60fb6fad6224f4f9f22e"
]
},
{
"name" : "3",
"Author" : []
}
]
},
{
"list" : "fea",
"cards" : [
{
"name" : "card",
"Author" : []
}
]
}
],
"__v" : 0 }
Router:
router.post('/add/member', function (req, res, next) {
console.log(req.body)
Board.findOneAndUpdate({ _id: req.body._id },
{
$set: {
lists : req.body.lists
}
},
{
upsert: true
},
((cards) => {
res.send(cards)
})
)
});
model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BoardSchema = new Schema({
name: { type: String, maxlength: 20 },
lists : { type: Array },
users : [{ type : Schema.Types.ObjectId, ref: 'User' }],
});
module.exports = mongoose.model('Board', BoardSchema);
And here is function with adding poeple
$scope.addMemberToCard = (indexList, indexCard, member) => {
$scope.board.lists[indexList].cards[indexCard].Author.push(member);
console.log( $scope.board.lists[indexList].cards[indexCard].Author)
return ApiService.staff.addMemberToCard($scope.board).then(function () {
})
}
You could use the mongoose Types ObjectID method and then transform the string sent into an ObjectID.
const id = new new mongoose.Types.ObjectId(Author);
Related
I have an json from backend:
{
"_embedded" : {
"countries" : [ {
"id" : 1,
"name" : "Brazil",
"code" : "BR",
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/countries/1"
},
"country" : {
"href" : "http://localhost:8080/api/countries/1"
},
"states" : {
"href" : "http://localhost:8080/api/countries/1/states"
}
}
}, {
"id" : 2,
"name" : "Canada",
"code" : "CA",
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/countries/2"
},
"country" : {
"href" : "http://localhost:8080/api/countries/2"
},
"states" : {
"href" : "http://localhost:8080/api/countries/2/states"
}
}
}
}
}
And on frontend, I want to get data according to typescript interface:
interface Country {
id: number;
code: string;
name: string;
}
I have a code which maps above json to interface:
getCountries(): Observable<Country[]> {
return this.httpClient.get<CountriesResponse>(this.countriesUrl).pipe(
map(response => <Country[]>response._embedded.countries)
)
}
interface CountriesResponse {
_embedded: {
countries: Country[]
}
}
But after mapping method still returns data which is not present in typescript interface Country, I mean _links field.
Please suggest how to avoid it.
I actually found some solution but still thinks it could be done better:
getCountries(): Observable<Country[]> {
return this.httpClient.get<CountriesResponse>(this.countriesUrl).pipe(
map(response => {
const data: Country[] = response._embedded.countries
return data.map(c => ({
id: c.id,
name: c.name,
code: c.code
}))
})
)
}
I have a 3 layer nested document something like this.
{
"_id" : ObjectId("5b5acaf0589ff6bfb5dd091f"),
"date" : "2018/07/31",
"clock" : [
{
"time" : "10:12:02",
"values" : [
{
"name" : "A1003",
"value" : "777"
},
{
"name" : "A0001",
"value" : "888"
}
]
},
{
"time" : "13:12:02",
"values" : [
{
"name" : "A1003",
"value" : "111"
}
]
}
]
}
I'm able to sort the date by using $gte $lte as below and all values are fetched.
getData(name: string[], fromDate: string, toDate: string): Promise<{ message: string }> {
return this._mongoUtility.testDb
.then(db => {
let collection = db.collection('TestDoc');
let fromOnlyDate = fromDate.split(' ');
let toOnlyDate = toDate.split(' ');
return collection.find({
'date': {
$gte: `${fromOnlyDate[0]}`,
$lte: `${toOnlyDate[1]}`
}
}).toArray();
})
.catch(err => {
return Promise.reject({message: 'Data not found', err: err})
})
}
I want to filter by using time and again by name and should display the value.
I tried in many ways but I'm getting the result. Is there nay other method to do so in MongoDB? Kindly suggest.
Expected output should look like below
0:{date: "2018/07/31 10:12:02", value-A1003: "777", value-A0001: "888"}
1:{date: "2018/07/31 13:12:02", value-A1003: "111"}
you can use the aggregate framwork to achive a simmler result(you cant create attr by value)
db.getCollection('sss').aggregate([
{$unwind:'$clock'},
{$unwind:'$clock.values'},
{$project:{
date: {$concat:[ "$date" ,' ' , "$clock.time" ]},
value:'$clock.values.value',
name:'$clock.values.name'
}}
])
I want to retrieve all the key values from a JSON file. For example in :
{
"total_count": 6,
"incomplete_results": false,
"items": [
{
"url": "https://api.github.com/repos/Samhot/GenIHM/issues/6",
"id": 293237635,
"number": 6,
"title": "Rechercher des documents",
"user": {
"login": "Samhot",
"id": 7148311
]
}
I would like to get :
["total_count", "incomplete_results", "items", "url", "url", "number", "title", "user", "login", "id"]
I have a function which return the content of my JSON in an observable :
getConfig(): Observable<any> {
return this.http.get<any>(this.myURL);
}
After that the data are reformated with .map to get only the keys with the Object.keys() function :
merge()
.pipe(
startWith({}),
switchMap(() => {
return this.getConfig();
}),
map(data => {
return Object.keys(data.items[0]);
}
)
)
.subscribe(data => {
this.dispo = data;
});
My problem is that i get only the keys that are in the level of the JSON I told
(data.items[0]) and not the ascendants or the descendants.
Of course I can create multiple requests but it asks to know in advance the structure of the JSON, what I want is to make it generic ...
How can I do to have an array with with all of my keys regardless of the structure of the JSON ?
Thanks in advance !
You would need to do a recursive function like:
function getDeepKeys(obj) {
const keys = Object.keys(obj);
const childKeys = keys
.map(key => obj[key])
.map(
value =>
Array.isArray(value)
? getDeepKeys(value[0])
: typeof value === "object"
? getDeepKeys(value)
: []
)
.reduce((acc, keys) => [...acc, ...keys], []);
return [...keys, ...childKeys];
}
const obj = {
total_count: 6,
incomplete_results: false,
items: [
{
url: "https://api.github.com/repos/Samhot/GenIHM/issues/6",
id: 293237635,
number: 6,
title: "Rechercher des documents",
user: {
login: "Samhot",
id: 7148311
}
},
{
url: "https://api.github.com/repos/Samhot/GenIHM/issues/6",
id: 293237635,
number: 6,
title: "Rechercher des documents",
user: {
login: "Samhot",
id: 7148311
}
}
]
};
console.log(getDeepKeys(obj));
Which then you would use like map(getDeepKeys). Note that this function assumes all the items in your array have the same schema.
this is the value i'm sending through postman tool
{
"name" :[
{
"first_name" : "antony",
"second_name" : "grijan"
},{
"first_name" : "suresh",
"second_name" : "muthu"
}],
"allergy" : [
{
"condition" : "headache"
},
{
"condition" : "toothache"
}],
"communication" : [
{
"address" : "no 21 big street",
"phone" : "84"
},
{
"address" : "no 43 small street",
"phone" :"87"
}]
}
I got the value in my control layer and i'm trying to save it in my mongodb using mongoose, my model code is
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var patientSchema = new Schema({
name: {
first_name : { type : String, default : ''},
second_name : { type : String, default : ''}
},
allergy : {
condition : {type : String, default : ''}
},
communication : {
address : {type : String, default : ''},
phone : {type : String, default : ''}
}
});
var patients = mongoose.model('Patients',patientSchema);
module.exports = patients;
My service layer code where i'm iterating is
var addDao = require('../dao/dao');
var async = require('async');
module.exports.addPatient = function(detail,callback) {
async.mapValues(detail,function(value,key,callback){
addDao.addPatient(value,function(data){
console.log(data);
console.log("calling");
callback(null, data);
})
}, function(err, result) {
// result is now a map of results for each key
console.log("inside func",result);
callback(result);
}
);
}
I have a console.log() in my service layer but it gives me only empty values, i think there is something wrong either with my model code or my iteration in my service layer!
I Am a newbie in MEAN-stack applications, I was trying to create one social media application in mean-stack. I created UserModel.js file to keep the user whole details which is given below,
UserModel.js file
var Address = {
pincode : "",
post : "",
city : "",
district : "",
state : "",
country : "",
};
var Privacy = {
public :true,
friendsOnly : false,
friendsOfFriendsOnly:false,
ImagepostPrivacy : false
};
var Education = {
primarySchool : "",
highSchool : "",
higherSecondary : "",
college : "",
};
var UserModel = {
id : "",
name : "",
lastname : "",
age : 0,
email:"",
phone:"",
username : "",
password : "",
active : true
};
function getUserModel(){
return{
userBasicDetails : UserModel,
userAddress : Address,
userPrivacy : Privacy,
userEducation : Education,
userFollowings : [],
userFollowers : [],
userFriends : []
}
};
module.exports.Usermodel = getUserModel;
I considered it as a POJO class of java, then In userService.js file I accessed this object and assigned the req.body() 's corressponding values to Usermodel and there I converted this Usermodel object to json and which worked as expected.
code for creating and inserting object for 'users' collection,
var userModel = require("../../../models/UserModel");
var con = require("../../database/DbConnection");
var userObject = null;
function registerNewUser(registerdata,callback) {
if(!validateInitialRegisteration(registerdata)){// some validation stuff
return callback(new Error("Invalid data"));
}else{
userObject = createUsedrObject(registerdata);
console.log("object before insertion %j",userObject);// got converted json
con.database().collection('users',function (err,usersCollection) {
usersCollection.insert(userObject,{w:1},function (err) {
if(err){
console.log("error %j",err);
callback(err,null);
}else{
callback(null,userObject);
}
})
});
}
}
/**
*This function will make the user collection object
**/
function createUsedrObject(obj){
var userObject = userModel.Usermodel();
userObject.userBasicDetails.name = obj.firstname;
userObject.userBasicDetails.password = obj.password;
userObject.userBasicDetails.username = obj.username;
return userObject;
}
And I got inserted the object to my 'users' named collection, Then I wrote function to retrieve data from 'users' named collection
function loginCheck(credentials,callback){
if(!credentials){
return callback(new Error("Invalid data"));
}else{
con.database().collection('users',function (err,usersCollection) {
if(err){
return callback(err,null);
}
else{
console.log("fetched data %j",usersCollection.find()); // here I am getting a log like 'fetched data [Circular]'
//callback(null,usersCollection.find());
}
});
}
};
expected json i consoled before insertion is given bellow
{ userBasicDetails:
{ id: '',
name: 'vishnu',
lastname: '',
age: 0,
email: '',
phone: '',
username: 'kr.vishnu401#gmail.com',
password: '1234',
active: true },
userAddress:
{ pincode: '',
post: '',
city: '',
district: '',
state: '',
country: '' },
userPrivacy:
{ public: true,
friendsOnly: false,
friendsOfFriendsOnly: false,
ImagepostPrivacy: false },
userEducation:
{ primarySchool: '',
highSchool: '',
higherSecondary: '',
college: '' },
userFollowings: [],
userFollowers: [],
userFriends: [] }
and the collection in db is
> db.users.find({"_id":ObjectId("581ae4994878ad1a84fa0c77")})
{ "_id" : ObjectId("581ae4994878ad1a84fa0c77"), "userBasicDetails" : { "id" : "", "name" : "vishnu", "lastname" : "", "age" : 0, "email" : "", "phone" : "", "username" : "vishnu#gmail.com", "password" : "123456", "active" : true }, "userAddress" : { "pincode" : "", "post" : "", "city" : "", "district" : "", "state" : "", "country" : "" }, "userPrivacy" : { "public" : true, "friendsOnly" : false, "friendsOfFriendsOnly" : false, "ImagepostPrivacy" : false }, "userEducation" : {"primarySchool" : "","highSchool" : "", "higherSecondary" : "", "college" : ""}, "userFollowings" : [ ], "userFollowers" : [ ], "userFriends: [ ] }
Since it is in Circular type I am not able to convert this object to json, but the inserted object I converted to json before db operation. I think somewhere I messed the concepts. If you have faced same problem please let me know.
usersCollection.find() is a function that takes a callback
try this instead
usersCollection.find().toArray(function(e, users) {
if (e) {
return callback(e, null);
}
console.log(users);
callback(null, users);
});
Documentation: https://mongodb.github.io/node-mongodb-native/api-generated/collection.html