Mongoose findOne and save new document [duplicate] - mongodb

This question already has answers here:
pushing object into array schema in Mongoose
(2 answers)
Closed 6 years ago.
I have a list of users that has 'hobby' object inside it.
User: {
name: John Doe,
hobby: {
[{hobby_id: 77777, hobby_name: hockey, hobby_type: sports}],
[{hobby_id: 88977, hobby_name: singing, hobby_type: talent}],
}
age: 27
}
now i want to findOne the user and add new hobby on the list. my first try is:
var user = User.findOne({ _id : req.body.user_id});
User.update(user, { hobby: [{ hobby_name: req.body.name ,
hobby_type: req.body.type }] },
function(err, user){
if(err){
return res.status(500).json(err);
}else{
return res.status(200).json(user);
}
});
however, with this code, everytime i call the function, my "NEW" hobby replaces the first one.
what can i do?

You can use the following code to do the same.
User.findByIdAndUpdate(req.body.user_id, {$push:{ hobby: [{ hobby_name: req.body.name ,
hobby_type: req.body.type }] }}, {safe: true}
function(err, user){
if(err){
return res.status(500).json(err);
}else{
return res.status(200).json(user);
}
});
And here findByIdAndUpdate is do both finding and updating the same document. no need to use callback or promises. Please refer the following link.

Your problem is that you are using whe repalce syntax, rather than the update syntax. I think you need:
user.hobbies.push({ hobby_name: req.body.name ,
hobby_type: req.body.type })

Related

Return only created subdocument mongoose

I need to push a new document into an array and use his _id.
Right now im using findOneAndUpdate, i know i can use { new: true } but i only need the created document and not the parent document.
this is my code so far
User.findOneAndUpdate(
{
'posts._id': req.params.id
},
{
$push: {
'posts.$.comments': {
from: {
_id: req.user._id,
username: req.user.username,
},
body: req.body.commentBody
}
}
},
err => {
if (err) console.log(err)
// Do something with ObjectId
}
);
Thanks in advance.
findOneAndUpdate callback gives you the updated document.
You have the Post's _id. You can use that to find the post to which you are adding the comment to. As you are pushing the comment, it will be the last element in the post array.
var mypost = doc.posts.find(function(post){
return post._id.toString()==req.params.id
});
console.log(mypost.comments[mypost.comments.length]._id)

MongoDB update nested array of object by index [duplicate]

This question already has answers here:
Update field in exact element array in MongoDB
(5 answers)
Closed 5 years ago.
Let's suppose to there is db like below...
{ _id: 1234,
key: 'Contacts',
value: [
{ name: 'McDonald', phone: '1111'},
{ name: 'KFC', phone: '2222'}
]
}
And I want to change KFC's phone number to '3333'.
What I did is
DB.findOne({ key: 'Contacts' }, function(err, db){
db.value[1]['phone'] = '3333'
db.save(function(err, result){
// done
})
}
)
But it didn't update the database. What am I wrong?
There's no specific _id in elements of array for some reason.
Only the way to find specific element is index.
Use the positional operator $
more info : https://docs.mongodb.com/manual/reference/operator/update/positional/#up.S
DB.update({key: "Contacts", "value.name": "KFC" },
{ $set: { "value.$.phone" : 666 } },function(err,doc){
});

MongoDB find then query nested document [duplicate]

This question already has answers here:
Retrieve only the queried element in an object array in MongoDB collection
(18 answers)
Closed 5 years ago.
I'm trying to make a 'like' route that find user by _id then query inside user.post an object id, so far I tried this:
User.find({
"_id": logged_user,
"posts_id": {
$elemMatch: req.body.id
}
}, (err, data) => {
if (err) {
res.json(err)
}
console.log(data);
})
Schema:
username: String,
posts:[{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}]
it returns an empty array '[]', how can I return true of false if it exists?
You are using $elemMatch wrong. It needs an object. Do it this way:
User.find({"_id":logged_user,"posts":{$elemMatch: {$eq : req.body.id}}},(err,data)=>{
if(err){
res.json(err)
}
console.log(data);
)

MongoDB, issue while iterating over a cursor [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I am not able to understand why the inserted MongoDB document although it contains items, the code is not able to iterate over. The cursor object itself is not null. I am able to retrieve the documents using db.newmongo.find()
var url = 'mongodb://localhost:27017/test';
MongoClient.connect(url, function(err, db) {
db.collection("newmongo").insert([{"name": "XXX", "age": "50"},
{"name": "YYY", "age": 43},
{"name": "ZZZ", "age": 27},
{"name": "AAA", "age": 29},
{"name": "BBB", "age": 34}]);
console.log("Connected correctly to server.");
var cursor=db.collection('newmongo').find();
console.log(cursor); // This gets logged
cursor.each(function(err, doc) {
if (doc != null) {
console.log('Document found');
} else {
console.log('Document not found');
}
});
You should always check if the records were inserted correctly without any errors. To do that you must pass a callback to the insert method. Something like this :
var url = 'mongodb://localhost:27017/test';
MongoClient.connect(url, function(err, db) {
if(err){
console.log("Error connecting to MongoDB");
return;
}
console.log("Connected correctly to server.");
db.collection("newmongo").insert([{name: "XXX", age: 50},
{name: "YYY", age: 43},
{name: "ZZZ", age: 27},
{name: "AAA", age: 29},
{name: "BBB", age: 34}], function(err, docs){
if(err){
console.log("Error inserting documents in MongoDB : " + JSON.stringify(err));
}
if(docs){
console.log("Following Documents were Successfully Inserted : \n" + JSON.stringify(docs));
}
});
Also since this is an async call, it will not wait till the inserting of documents is done and will fire the find instantly. Due to this, you might not be able to get any records in the newmongo collection as the write operation is still in progress.
So what I suggest is to call find only after the if(docs) condition.
And I also think that calling find is not necessary as the docs parameter that was returned in the callback would return the docs successfully written in your collection. So you can directly log them to console as shown in the above example.

How to get string value inside a Mongodb document?

I have this document stored in mongodb document:
{
"_id":ObjectId("4eb7642ba899edcc31000001")
"hash":"abcd123"
"value":"some_text_here"
}
I am using NodeJS to access the database:
collection.findOne({'hash' : req.param('query') },
function(err, result){
console.log(res);
});
The result of this query is the whole document, however I need to get only the "value" text: "some_text_here"
How can this be done?
You can specify the fields that you are interested in (_id will always be returned, though):
collection.findOne({'hash': req.param('query') },
{fields: ['value'] },
callbackFunction );
You can do it such way:
collection.findOne({'hash' : req.param('query') },
function(err, result){
console.log(result.value);
});