A simple json response for Post.find().populate("name") will return json result as follow. Note: The focus of the question is to rearrange the "name":"Alex" in json to the final structure as shown. Ignore the part that need hiding _id and __v. Thanks.
[
{
"_id": "54cd6669d3e0fb1b302e54e6",
"title": "Hello World",
"postedBy": {
"_id": "54cd6669d3e0fb1b302e54e4",
"name": "Alex",
"__v": 0
},
"__v": 0
},
...
]
How could i rearrange and display the entire json as follow?
[
{
"_id": "54cd6669d3e0fb1b302e54e6",
"title": "Hello World",
"name": "Alex"
},
...
]
You can use the lean() method to return a pure JSON object (not a mongoose document) that you can then manipulate using lodash helper methods such as map(), like in the following example:
Post.find()
.populate("name")
.lean().exec(function (err, result) {
if(result){
var posts = _.map(result, function(p) {
p.name = p.postedBy.name;
p.postedBy = undefined;
return p;
});
console.log(posts);
}
});
You can disable the "__v" attribute in your Schema definitions by setting the versionKey option to false. For example:
var postSchema = new Schema({ ... attributes ... }, { versionKey: false });
As follow-up to your question on rearranging the order of the properties in the JSON, JS does not define the order of the properties of an object. However, you
can use both the JSON.parse() and JSON.stringify() methods to change the order, for example
var json = {
"name": "Alex",
"title": "Hello World",
"_id": "54cd6669d3e0fb1b302e54e6"
};
console.log(json);
//change order to _id, title, name
var changed = JSON.parse(JSON.stringify(json, ["_id","title","name"] , 4));
console.log(k);
Check the demo below.
var json = {
"name": "Alex",
"title": "Hello World",
"_id": "54cd6669d3e0fb1b302e54e6"
};
//change order to _id, title, name
var changed = JSON.parse(JSON.stringify(json, ["_id","title","name"] , 4));
pre.innerHTML = "original: " + JSON.stringify(json, null, 4) + "</br>Ordered: " + JSON.stringify(changed, null, 4);
<pre id="pre"></pre>
Related
"
success": true,
"result": {
"values": {
"asdf": [],
"dj": [
{
"id": 18,
"ownerId": "5b0b3932-e262-4ac4-923c-13daf2bd4a3c",
"ownerName": "tester",
"name": "masr",
"description": "she was and firebase have also had to make their decision and make the beg to 8be 8the 8same 6th 7century 8of 8and 6and 88th century ones in flutter take on my favourite ",
"statusId": "PENDING",
"status": null,
"price": 9000.00,
"isPublic": false,
"startDate": "2022-05-26T00:00:00",
"expectedEndDate": "2022-05-27T00:00:00",
"finishDate": null,
"interests": [
{
"id": "my-first-interest",
"isDeleted": false
},
{
"id": "gdg",
"isDeleted": false
},
{
"id": "dj",
"isDeleted": false
}
]
},
]
}
}
the dynamic key is asdf and dj change form user to anoter
i want to get id or ownername .... etc without object can any one help me in this cause
Since you don't know the key name in advance, you will have to iterate over all of them looking for JSON object members that look like they contain ID and owner. Something like this:
import 'dart:convert';
import 'dart:io';
void main() {
final decoded = json.decode(File('json1.json').readAsStringSync());
// values will be a JSON object
final values = decoded['result']['values'] as Map<String, dynamic>;
// values.values will be all of the JSON arrays in that object
// do a whereType just to rule out any other fields in the JSON object
// use expand to merge all lists together
// and wheretype again to double check that we only have JSON objects
// further check that only JSON objects with the right values are selected
// and map these to PODOs
final result = values.values
.whereType<List>()
.expand((e) => e)
.whereType<Map>()
.where((e) => e.containsKey('id') && e.containsKey('ownerId'))
.map<IdAndOwner>((m) => IdAndOwner(m['id'], m['ownerId']))
.toList();
print(result); // prints [Id/OwnerId=18/5b0b3932-e262-4ac4-923c-13daf2bd4a3c]
}
class IdAndOwner {
final int id;
final String ownerId;
IdAndOwner(this.id, this.ownerId);
#override
String toString() => 'Id/OwnerId=$id/$ownerId';
}
I want to search the key "AylaHeartBeatFrequency" inside nested json. how to search and get its value ? in flutter/dart
{
"sAWSIoT": {
"CloudStatus": 1,
"PairingFlag": 0,
},
"sDebug": {
"LocalDebugMsg_d": "Model ID",
"AylaHeartBeatFrequency": 0
},
"Product": {
"Mode": 1,
"Model": "abc"
},
"data": {
"DeviceType": 300,
"Endpoint": 0,
"UniID": "0000000000000000"
}
}
You can do:
var map = /*put your json here. You can use json.decode() on the json if it's not yet formatted*/, value;
for(var item in map.values) {
if(item.containsKey('AylaHeartBeatFrequency') value = item['AylaHeartBeatFrequency']) ;
}
I am very new to MongoDB and mongoose I have a model name called agent
agent.model.js
const mongoose = require('mongoose')
const agentSchema = new mongoose.Schema({
agent: {
type: String,
required: true
}
})
const Agent = mongoose.model('Agent', agentSchema)
module.exports = Agent;
Now I have a array of string:
const agentName = ['john', 'alex', 'david'];
Now I want to store this array into the mongoDB as an individual agent.
like this:
[
{
"_id": "6000977d9b94f52960955066",
"agent": "john",
"__v": 0
},
{
"_id": "6000977d9b94f52960955067",
"agent": "alex",
"__v": 0
},
{
"_id": "6000977d9b94f52960955068",
"agent": "david",
"__v": 0
}
]
Note: Right now First I am converting my array of string into the array of object using loop like this:
agentName = agentName.map((e) => {return {agent: e}})
//output of above line of code
[ { agent: 'Alex Watson' },
{ agent: 'John Snow' },
{ agent: 'Rita Ora' } ]
Then I am saving the agentName.
But I am looking for some better approach, Like in which there is no need of converting the array of string into the array of object.
you must to use insertMany() function is used to insert multiple documents into a collection. It accepts an array of documents to insert into the collection. like following code, so have to create a array of abjects, that you created
note: in your question define const agentName next step assign result of map to the constant variable, so this is wrong
const agentName = ['john', 'alex', 'david'];
let arr = agentName.map((e) => {return {agent: e}})
Agent.insertMany(arr).then(function(){
console.log("Data inserted") // Success
}).catch(function(error){
console.log(error) // Failure
});
How I will check current user id == id and show user like or not in UI
"reference":[
{
"id":"123",
"userid"234"
},
{
"id":"1423",
"userid"25534"
},
{
"id":"15423",
"userid"2335534"
},
]
if this is json response try to convert it in models using https://javiercbk.github.io/json_to_dart/
or here is code that can work for u
var reference = [
{"id": "123", "userid": "234"},
{"id": "1423", "userid": "25534"},
{"id": "15423", "userid": "2335534"},
];
var r = reference.firstWhere((e) => e["id"] == "123");
print(r);
// output
{id: 123, userid: 234}
So I have the following schema:
var List = new Schema(
{
item_details_template: {
default: [
{
"title": "Name",
"content": "",
"hidden": false,
"order": 0,
"the_type": "text"
},
{
"title": "Price",
"content": "",
"hidden": false,
"order": 1,
"the_type": "text"
},
{
"title": "Company",
"content": "",
"hidden": false,
"order": 2,
"the_type": "text"
}
],
type: [Item_Detail]
}
}
)
However, I don't want ONLY this schema (subdocument) to not create _id fields. How do I do this? I know you can change the original schema itself, but it's being used by other Schemas, where I would like the _id to be populated.
To suppress _id on the item_detail_template, you need to restructure the way you create subdocument as follows
var mongoose = require("mongoose");
var subSchema = mongoose.Schema({
//your subschema content
},{ _id : false });
var schema = mongoose.Schema({
// schema content
subSchemaCollection : [subSchema] // item_details_template
});
var model = mongoose.model('tablename', schema);
If you want to suppress _id on the item_detail_template in the List schema only:
var List = new Schema(
{
item_details_template: {
_id:false, // should supress _id property
default: [
...
var widgetSchema = new Schema({ ... attributes ... }, { versionKey: false });