mongoose find json inside layers json - javascript

queueModel.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var queueSchema = Schema({
title: String,
description: String,
abc:{
a1: String,
b1: String,
c1: String
},
});
var Queue = mongoose.model('Queue', queueSchema);
module.exports = Queue;
api1.js
Queue.findOne({ title: "zzzz"} ).exec((err, data) => {
if (err) console.log(err)
else console.log(data)
});
result is data ...
api2.js (problem)
Queue.findOne({ title: "zzzz", abc:{a1: "aaaa"} } ).exec((err, data) => {
if (err) console.log(err)
else console.log(data)
});
Why is it null?
I want to use a1 condition.
Ask a Solution.
Do not modify the schema.

Try this:
Queue.findOne({ title: "zzzz", "abc.a1": "aaaa"} } ).exec((err, data) => {
if (err) console.log(err)
else console.log(data)
});
To filter on the abc you need to do abc.a1 as the field.

Related

How to set $inc in a mongoose model instance when using .save()?

This is my schema:
const Schema = mongoose.Schema;
const urlSchema = new Schema({
original_url: String,
short_url: Number
});
Then I do this:
let urlInstance = new Url({ original_url: url, { $inc: { 'short_url': 1 }} });
urlInstance.save((err, doc) => {
if (err) return console.error(err);
console.log("saved ", doc);
res.json(doc);
});
also tried it like this:
let urlInstance = new Url({ original_url: url });
urlInstance.save(({ $inc: { 'short_url': 1 }}), (err, doc) => {
if (err) return console.error(err);
console.log("saved ", doc);
res.json(doc);
});
I don't know how to pass the $inc bit in without it complaining about syntax. What am I doing wrong here? Tried different ways and even using mongoose-sequence but seems like $inc should be easier?

Unable to save to an asssociate array in mongodb using mongoose

var mongoose = require("mongoose"),
campground = require("./models/campground"),
comment = require("./models/comment");
var data = [{
name: "Offside Lake",
image: "https://images.unsplash.com/photo-1504280390367-361c6d9f38f4?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
description: "Whatever evrr"
},
{
name: "Reality Check",
image: "https://images.unsplash.com/photo-1517824806704-9040b037703b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
description: "wabdiwyu"
},
{
name: "Wawu Land",
image: "https://images.unsplash.com/photo-1508873696983-2dfd5898f08b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
description: "Just be feeling Wawu"
}
];
var text = {
text: "Hullabaloo",
author: "Olalaa"
};
campground.comments = new Array();
function seedDB() {
campground.deleteMany({}, function(err) {
if (err) {
console.log(err);
} else {
console.log("removed");
data.forEach(function(camp) {
campground.create(camp, function(err, camp) {
if (err) {
console.log(err);
} else {
console.log("Successfully added");
comment.create(text, function(err, comment) {
if (err) {
console.log(err);
} else {
campground.comments.push(comment);
campground.save();
console.log("comment added");
}
});
}
});
});
}
});
}
I have two mongoose models campground and comment. Inside the campground schema, I have the comments associative array in the campground schema. I am trying to add comments to my comments array but I am getting the error - campground.save is not a function. Even tried campground.markModified("comment") then campground.save(), getting the same error
//my campground schema
var mongoose = require("mongoose");
var campSchema = new mongoose.Schema({
name: String,
image: String,
description: String,
comments: [{
type: mongoose.Schema.Types.ObjectId,
ref: "comment"
}]
});
module.exports = mongoose.model("Camp", campSchema);
//my comment schema
var mongoose = require("mongoose");
var commentSchema = mongoose.Schema({
text: String,
author: String
})
module.exports = mongoose.model("comment", commentSchema);
If I understand what you are trying to do, you are trying to create a campground and place the comments inside.
If that is so, then the code may look something like this (placed everything in one file):
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true});
var data = [
{
name: "Offside Lake",
image: "https://images.unsplash.com/photo-1504280390367-361c6d9f38f4?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
description: "Whatever evrr"
}, {
name: "Reality Check",
image: "https://images.unsplash.com/photo-1517824806704-9040b037703b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
description: "wabdiwyu"
}, {
name: "Wawu Land",
image: "https://images.unsplash.com/photo-1508873696983-2dfd5898f08b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
description: "Just be feeling Wawu"
}
];
const comment = mongoose.model('comment', new mongoose.Schema({
text: String,
author: String
}));
const campground = mongoose.model('Camp', new mongoose.Schema({
name: String,
image: String,
description: String,
comments: [{
type: mongoose.Schema.Types.ObjectId,
ref: "comment"
}]
}));
var text = {
text: "Hullabaloo",
author: "Olalaa"
};
campground.deleteMany({}, function(error) {
if (error) {
console.error(error);
return;
}
console.log("Removed");
data.forEach(function(camp) {
campground.create(camp, function(error, newCamp) {
if (error) {
console.error(error);
return;
}
console.log("Successfully added");
comment.create(text, function(err, newComment) {
if (err) {
console.error(err);
return;
}
newCamp.comments.push(newComment);
newCamp.save();
console.log("Comment added");
})
});
})
})
The problem was due to the fact that you kept the same name throughout and that might have confused you a bit.
What you wanted to do was camp.comments.push(comment) camp.save() instead of campground.comments.push(comment) and campground.save() respectively.
As a friendly advice:
Switch to using promises instead of callbacks, you may set yourself up for what is known as Callback hell
As much as possible try not to rely on the closure nature of JavaScript and keep naming your variables the same throughout. That leads to problems like what you are experiencing now

MongoDB return empty object

I am trying to fetch info from my mongodb database but it keeps returning an empty object. I've used exactly same for fetching info from a collection called "users" and it works but not with anything else.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var url = 'mongodb://test:test#124.355.99.268:27017/admin';
mongoose.connect(url);
var userPBData = new Schema ({
_id: mongoose.Schema.Types.ObjectId,
email: String,
password: String,
token: String,
name: String,
phone: String
});
var UserPB = mongoose.model('user_pb', userPBData);
UserPB.find( function(err, rows){
if(err) {
console.log(err);
}else{
console.log(rows);
}
})
The database document inside "user_pb:
{
"_id":"5ab6815820568524b570f818",
"email":"test#test.se",
"password":"dac2cc2b9bfc297f2ecebe3bc98a0d248",
"token":"6c4c10d6e2c1067faa3ff8aad0d8542b3a5e55f805bab397b18ca16b8f986a0c4",
"name":"Test",
"phone":"har ej"
}
The console output:
[]
What am i doing wrong?
Thank you very much for the help!
UserPB.find( function(err, rows){
if(err) {
console.log(err);
}else{
console.log(rows);
}
})
first argument for query should be a selector. then you should put call back.
UserPB.find({}, function(err, rows){
if(err) {
console.log(err);
}else{
console.log(rows);
}
})

how to get key value from json result in node js

how can I get specify email and its value only, from JSON array result which should be like=>only( email: abc#gmail.com)
here is my code:
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("Scream_It");
var query = { bid_location : 'abbottabad' };
dbo.collection("bid_placement").find(query).sort({bid_amount:-1}).limit(1).toArray(function(err, result){
if (err) throw err;
console.log(result);
// console.log(JSON.stringify(result));
var string = JSON.stringify(result);
console.log(string);
var objectValue = JSON.parse(string);
// console.log(objectValue);
console.log(objectValue.email);
this is the result which i am getting in console
[ { _id: 5a9f8849fc49ca1ff4aee3dc,
email: 'abc#gmail.com',
bid_amount: '200',
bid_time: '22:22:22:22',
bid_location: 'abbottabad',
bid_status: 'false' } ]
This is a simple JavaScript:
var res = [
{ _id: '5a9f8849fc49ca1ff4aee3dc',
email: 'abc#gmail.com',
bid_amount: '200',
bid_time: '22:22:22:22',
bid_location: 'abbottabad',
bid_status: 'false' },
{ _id: '5a9f8849fc49ca1ff4aee3dd',
email: 'abcd#gmail.com',
bid_amount: '200',
bid_time: '22:22:22:22',
bid_location: 'abbottabad',
bid_status: 'false' },
{ _id: '5a9f8849fc49ca1ff4aee3de',
email: 'abcde#gmail.com',
bid_amount: '200',
bid_time: '22:22:22:22',
bid_location: 'abbottabad',
bid_status: 'false' }
];
var finalRes = res.map(({email}) => ({email}));
console.log(finalRes);
You can use reduce or map on your array:
Using reduce
reducedResults = result.reduce((accumulator, current) => {
accumulator.push({ email: current.email });
return accumulator;
}, [])
Using map
mappedResults = result.map((user) => {
return { email: user.email };
})
You could use select method from mongoose api. Basically, you can control with it what will result object contains of its properties. So, your code could look like this:
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("Scream_It");
var query = { bid_location : 'abbottabad' };
dbo.collection("bid_placement").find(query).select({email: 1, _id: 0}).sort({bid_amount:-1}).limit(1).toArray(function(err, result){
if (err) throw err;
console.log(result);
// console.log(JSON.stringify(result));
var string = JSON.stringify(result);
console.log(string);
var objectValue = JSON.parse(string);
// console.log(objectValue);
console.log(objectValue.email);
You should get something like this:
[ { email: 'abc#gmail.com'} ]
If you need _id, use this in select {email: 1, _id: 1}

mongodb Error mongoose do not push object in array $pushAll

I have a simple app with User and Post models,
var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/assoc", {useMongoClient:true});
mongoose.Promise = global.Promise;
//Post
var postSchema = new mongoose.Schema({
title: String,
content: String
});
var Post = mongoose.model("Post", postSchema);
//User
var userSchema = new mongoose.Schema({
email: String,
name: String,
posts: [postSchema]
});
var User = mongoose.model("User", userSchema);
I Create a user before (name: "gino") and push a post into:
// var newUser = new User({
// email: "a.b#c.it",
// name: "gino"
// });
//
// newUser.posts.push({
// title: "gino's post",
// content: "this is content"
// });
//
// newUser.save(function (err, user) {
// if (err) {
// console.log(err);
// } else {
// console.log(user);
// }
// });
Also create another post to check if Post model works:
// var newPost = new Post({
// title: "honky",
// content: "tonky"
// });
//
// newPost.save(function (err, post) {
// if (err) {
// console.log(err);
// } else {
// console.log(post);
// }
// });
When I try to find "gino" and push a new item into the posts array I have an error trying to save user (user.save) with this snippet:
User.findOne({name: "gino"}, function (err, user) {
if (err) {
console.log(err);
} else {
console.log(user);
user.posts.push({
title: "post",
content: "content"
});
user.save(function (err, user) {
if (err) {
console.log(err);
} else {
console.log(user);
}
});
}
});
When I run the app i got this:
{ MongoError: Unknown modifier: $pushAll
at Function.MongoError.create (appFolder\node_modules\mongodb-core\lib\error.js:31:11)
at toError (appFolder\node_modules\mongodb\lib\utils.js:139:22)
at appFolder\node_modules\mongodb\lib\collection.js:1059:67
at appFolder\node_modules\mongodb-core\lib\connection\pool.js:469:18
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
name: 'MongoError',
message: 'Unknown modifier: $pushAll',
driver: true,
index: 0,
code: 9,
errmsg: 'Unknown modifier: $pushAll' }
Someone can help me?
Try using findOneAndUpdate instead.
User.findOneAndUpdate(
{ name: "gino" },
{ $push: { posts: { title: 'post', content: 'content' } } },
{ new: true },
function (err, user) {
if(err) console.log("Something wrong when updating data");
console.log(user);
});
Hope it helps!
If you are using 3.5 MongoDB version or higher, can be an issue with $pushAll, which is deprecated.
I founded an option to work around setting usePushEach to true:
new Schema({ arr: [String] }, { usePushEach: true });
Founded in:
https://github.com/Automattic/mongoose/issues/5574#issuecomment-332290518
Can be useful to use the with .push.

Categories

Resources