I'm trying make CRUD operation in Electron, where using MongoDB, and Mongoose for Electron connect to database.
I have a function list for return the "return" of Mongoose. When I debugging return data, is show correct in my terminal
ipc.on('products.list', function(event, query) {
Service.list(query, function(err, data) {
console.log(data); // this will be print correct result
event.sender.send('product.list', data);
});
});
Result of code upper part:
[ { _id: 55c15f2981260a6f0ef8a657,
__v: 0,
deleted_at: '',
updated_at: '',
created_at: Tue Aug 04 2015 21:51:52 GMT-0300 (BRT),
measure: '',
aplication: '',
model: 'Mode XBA',
reference: 'Reference test 123',
code: '2028' } ]
But when I debug return data by client side with fallowing code, result is not correct and is not equal server side print.
Client side code:
ipc.on('product.list', function(data) {
window.data = data;
console.log(data); // this will print incorrect result
});
ipc.send('products.list', {});
Result of client side received:
{
"$__":{....},
"_doc":{...},
"_posts":{...},
"_pres":{...},
"isNew":false
}
Contains more objects in each element.
Why this happens? How to can I resolve this problem?
I resolved this problem!
This return is result from Mongoose
{
"$__":{....},
"_doc":{...},
"_posts":{...},
"_pres":{...},
"isNew":false
}
For return only property, is need add options {lean : true}
Ex:
Model.find(this.query)
.lean()
.exec(function(err, data) {}
);
More detail in Mongoose Doc
Related
I'm currently writing a small Twitter app using the Twit API. To do what I need to do, I'd like the data to be able to be filtered by user id, and not get all the other garbage JSON spits out. Here's what the response looks like:
{ created_at: 'Sat Jun 23 03:45:13 +0000 2018',
id: 1010368149466697700,
id_str: '1010368149466697728',
text:
'RT #ClassicIsComing: "Let\'s Talk ETC!" Podcast Series by #chris_seberino of #InputOutputHK \nA deep series of powerful intervie
ws with influ…',
truncated: false,
entities:
{ hashtags: [],
symbols: [],
user_mentions: [ [Object], [Object], [Object] ],
urls: [] },
source:
'TweetDeck',
in_reply_to_status_id: null,
in_reply_to_status_id_str: null,
in_reply_to_user_id: null,
in_reply_to_user_id_str: null,
in_reply_to_screen_name: null,
user:
{ id: 759252279862104000,
id_str: '759252279862104064',
name: 'Ethereum Classic',
screen_name: 'eth_classic',
location: 'Blockchain',
description:
'Latest News and Information from Ethereum Classic (ETC). A crypto-currency with smart contracts which respects immutability a
nd neutrality.',
url: ,
entities: { url: [Object], description: [Object] },
protected: false,
followers_count: 216255,
friends_count: 538,
listed_count: 2147,
etc. The code i'm using to get this is:
T.get('statuses/home_timeline', {count: 1, exclude_replies: true},
function(err, data, response){
if (err){
console.log('Uh oh, we got a problem');
}
else{
console.log('We GUUCie bruh');
}
var tweets = data;
/* for (var i = 0; i < tweets.length; i++) {
console.log(tweets[i]);
} */
console.log(data);
});
the last block of code is commented out because I've attempted to define "tweets" as data.id, data.statuses.id, etc, but everything seems to spit out "undefined." I'm a complete noob to javascript and JSON as I'm only currently learning C++ # school, so any help would be appreciated!
edit
I thought I'd add in the error message to show you what happens when I try to treat the data as an object.
If I try to use JSON.parse(data) as the value for my tweet variable:
T.get('statuses/home_timeline', {count: 1, exclude_replies: true}, callBackFunction)
function callBackFunction(err, data, response){
if (err){
console.log('Uh oh, we got a problem');
}
else{
console.log('We GUUCie bruh');
}
var tweets = JSON.parse(data);
//for (var i = 0; i < tweets.length; i++) {
// console.log(tweets[i].id_str);
// }
console.log(tweets.id_str);
}
I get:
$ node crypt.js
the bot is starting
We GUUCie bruh
undefined:1
[object Object]
^
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
If I try to treat it as an object right away, with:
function callBackFunction(err, data, response){
if (err){
console.log('Uh oh, we got a problem');
}
else{
console.log('We GUUCie bruh');
}
var tweets = data.id_str;
//for (var i = 0; i < tweets.length; i++) {
// console.log(tweets[i].id_str);
// }
console.log(tweets);
}
I get:
$ node crypt.js
the bot is starting
We GUUCie bruh
undefined
Have you tried JSON.parse?
So your line "var tweets = data;" would be "var tweets = JSON.parse(data);"
From there you should be able to interact with the data as if it were an object and grab specifically the id or whatever you're looking for.
I'm also a noob, so I don't have an in depth explanation as to why this works, but it helped fix an issue I had when pulling data from API.
I have a code like, I have a problem with sending response.
socket.on('findUserMessages', (userName) => {
io.sockets.connected[socket.id].emit('Checking-message', {
type: 'ss',
text: bot,
user: 'bot'
});
var dupa = db.chat.find({ user: userName }, function(err, docs) {
userName = userName
if (err) throw err;
console.log('load old messages', docs)
})
io.emit('private message', dupa);
})
My node console output is like
[ { _id: 5888bdd6cef7952e38821f35,
text: 'O rajciu rajciu',
user: 'Adam',
time: 2017-01-25T15:01:42.733Z }]
I know that output is not a JSON string, how to solve that? I was trying to use .toArray() but without succes.
That might be silly question but I am stuck with it for a long time.
Convert to json your result before emitting it. Try to emit JSON.stringify(dupa).
EDIT
Your output is actually JSON already (JSON array), so if you want to get only JSON string on client side, convert your output to string there (JSON.strigify(result) on client side on receiving the emit event).
It's to my understanding that there is no .toObect() in JavaScript but it is used in mongoose to change the mongoose documents to an object so you can use JavaScript built in functions.
I don't have a grasp on when to use it. sometimes when i get an array of docs I could use forEach on the returned array and then other times I would spend 20 minutes working out why the forEach doesn't work. then I would add .toObject to the returned Array and the forEach would work. something like that. I'm not sure about my memory if it was forEach or something else.
Anyways this is the latest weird issue. I'm in EJS and I needed to do <% console.log("typeof", user.toObject().hasOwnProperty("facebook")) %> to work instead of <% console.log("typeof", user.hasOwnProperty("facebook")) %> . The one with the .toObject() consoles : typeof true the one without consoles typeof false . That seems weird to me. Is user a mongoose document? How could I use .toObject in ejs? Oh wait a minute. Im just thinking is it because it is in the "<%%>" it gets connected to the server side code and maybe I have mongoose required in my server.js Why did I have to use toObject to get the true value?
any ways I didn't think I needed to use .toObject()
This is what I have in my .js file : res.render("editProfile", {aboutUser : returnedUser, user : req.user}); I think req.user is from passport not mongoose.
user obj
{ _id: 581a2chan3changed727, defaultImage: 'https://scontefrfrxxffbcdn.net/v/t1.0-1/s148x148/29731_575634691740_1085883_n.jpg?oh=797bc81addf3611309changedoe=588AC839', urlname: 'Jacchanged', momented: 'Nov 2, 2016', username: 'Jack Schuldenfrei', __v: 0, usefulness: [], createdOn: Wed Nov 02 2016 14:15:47 GMT-0400 (Eastern Daylight Time), shortId: 'rkn8powgl', pointsRecord: [], repPoints: 0, facebook: { posts: '{"email":"jschuldenfreiGTGTGTgchanged,"name":"Jack Schuchange","gender":"male","picture":{"data":{"height":148,"is_silhouette":false,"url":"https:\\/\\frfr.net\\/v\\/t1.0-1\\/s148x148\\/29731_575634691740_1fr5883_n.jpg?oh=797bc81addf36113e0933a67eef32ab9&oe=588AC839","width":93}},"id":"10100584555845400"}', gender: 'male', email: 'jschuldenfredu', name: 'Jack changes', token: 'EAAPs693O1UMBAHwTcyZAPtRiXrwvxrBWhGCJZCQlAIfHRZAiCLY3tYDVoviB4yDrK68WrsUnuxlcHfUJE984aAvWOnFZASqbUjYZAhHnsL0mFCZCNRQwsn3oJn1acu1qnSPFko6I3ShZAtPIMumrVlpVxR0ZD', id: '1010058386584400' }, reviews: [] } { _id: 581a2d53380e4c70ac728, userId: 581a2d380e4c7037aac727, username: 'Jack changed', urlname: 'Jachanged', __v: 0, question1: { name: 'This is for question1' } }
I get that user object by doing <%=user%> in the ejs file.
What you want is .lean()
Usually passport has a serialization configuration that looks like
// Serialize sessions
passport.serializeUser(function (user, done) {
done(null, user.id);
});
// Deserialize sessions
passport.deserializeUser(function (id, done) {
User.findOne({
_id: id
}, '-salt -password', function (err, user) {
done(err, user);
});
});
Change the deserialization process like
// Deserialize sessions
passport.deserializeUser(function (id, done) {
User.findOne({
_id: id
}, '-salt -password')
.lean() // lean converts mongoose.Document to Plain Javascript Object
.exec(function (err, user) {
console.log(user instanceof mongoose.Document) // false
done(err, user);
});
});
I have my object as follows
-Notifications
userId
key1
datakey1
date: 10-10-2016
time: 3:20 pm
status: open
key2
datakey2
date: 11-10-2016
time: 5:00 pm
status: close
I'm having ref path till Notifications/userId
How do I retrieve data where status='open'
Code from comments:
ref.orderByChild("status")
.equalTo('open')
.on("value", function(snapshot) { console.log(snapshot.key); });
Firebase queries can only contain one dynamic key.
In your case you have two dynamic keys under that key1/key2 and datakey1/datakey2. You'll either have to put one of those at a fixed location (e.g. key1/my/status, key2/my/status) or you will have to structure your data differently.
notificationsStatusPerUser
userId: {
key1_datakey1: {
status: "open",
path: "key1/datakey1"
}
key2_datakey2: {
status: "close",
path: "key2/datakey2"
}
}
}
Now you can find all open items for a specific user with:
var query = ref.child('notificationsStatusPerUser')
.child(uid)
.orderByChild(status)
.equalTo('open');
query.on('child_added', function(snapshot) {
ref.child('notifications')
.child(uid)
.child(snapshot.val().path)
.once('value', function(linkedSnapshot) {
console.log(linkedSnapshot.val());
});
};
I have to try to store my child info into MongoDB via using postman tool. But it shows me this message "message": "child info validation failed"
in postman console. child info is my collection name where I store my child info.
my requirement is to store the result in array form as below schema mentioned inside MongoDB
1). This is js child schema
userId:{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
quiz:[
{
questionId:{
type: mongoose.Schema.Types.ObjectId,
ref: 'questions'
},
score:{type:String},
time:{type:String}
}
]
2). This is node js
try {
var quizArr = [];
var quizObj = {
'questionId': req.params.questionId,
'score': req.params.score,
'time': new Date().toISOString()
};
quizArr.push(quizObj);
var userObj = {
'userid': req.params.userId,
'quiz': quizArr
};
//var parseObj = Json.stringify(userObj); This line is comment
var childinfoSave = new QuizChildInfo(userObj);
childinfoSave.save(function (err) {
if (err) return next(err);
res.send("Child questionId score and date saved successfully")
console.log("Child questionId score and date saved successfully");
});
}catch(err){console.log(err);}
3). Output of postman screen
{
"message": "childinfos validation failed"
}
4). Output of console
Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
5). Mongo console
{
"_id" : ObjectId("57bc483169e718642ac0ac44"),
"levelsAttempted" : [ ],
"quiz" : [ ],
"__v" : 0
}
For the problem of your console,
put mongoose.Promise = global.Promise; in the file where you have established your server connection( like in my case its index.js).
And i think you may have not posted the whole code as i couldnt find childinfos in your code.