update a record in mongodb through mongoose - node.js

I tried to update existing record in a collection of mongodb. existing record is {UserName: "niren",AccessToken:"abced",RefreshToken:"fghigh"} and I want to update as {UserName: "niren",AccessToken:"mobile",RefreshToken:"phone"}. I used following code but it's not working.
myModel.update({UserName:"niren"},{$inc:{AccessToken:"mobile",RefreshToken:"phone"}},function(err){
if(err){
console.log("some error happened when update");
}
else{
console.log("update successfull! with name = " + "niren");
myModel.findOne({UserName:"niren"}, function(err, users) {
console.log("updated : " + users);
});
}
})

It was my mistake, I shouldn't use $inc. I should have used {AccessToken:"mobile",RefreshToken:"phone"} instead of {$inc:{AccessToken:"mobile",RefreshToken:"phone"}}. Now its working fine.

Related

Nodejs, MongoDB asynchronous callback problem

I'm the beginner of nodejs and MongoDB.I tried to design RESTAPI but there was a problem.
Here is my router code.
app.post('/fcm',function(req,res){
var beaconid = req.body.beacon_id;
var my_token_id = req.body.user_id;
User.find({beacon_id: beaconid}, function(err, output){
if(err) return res.status(500).json({error: err});
if(!output) return res.status(404).json({error: 'user not found in User collections.'});
console.log("output user id :"+output.user_id + " beacon: " +output.beacon_id );
target_token_id = output.user_id;
res.json(output);
});
});
And this is user schema.
var userSchema = new Schema({
user_id: String,
beacon_id: String
});
The result of above function in the console is:
output user id: undefined , beacon: undefined.
But json from res function is printed properly.
This codes look like very simple but I don't know what is the problem.
Please somebody help me.
By using find, you are expecting 1 document or more. This means that the method <Model>.find() should logically return an array. You can make sure that is what happens by logging the output just after the query to make sure it is an array of documents.
To solve your problem, you can either access the document at index 0 of the array:
User.find({beacon_id: beaconid}, function(err, output){
if(err) return res.status(500).json({error: err});
if(!output) return res.status(404).json({error: 'user not found in User collections.'});
console.log("output user id :"+output[0].user_id + " beacon: " +output[0].beacon_id );
target_token_id = output[0].user_id;
res.json(output);
});
Or use findOne() instead, that returns only one document.
User.findOne({beacon_id: beaconid}, function(err, output){
if(err) return res.status(500).json({error: err});
if(!output) return res.status(404).json({error: 'user not found in User collections.'});
console.log("output user id :"+output.user_id + " beacon: " +output.beacon_id );
target_token_id = output.user_id;
res.json(output);
});

How to retrieve the value from the mongoose query

I am a beginner in nodejs and mongoose. I am trying to retrieve the category value which astname having laptop. Please suggest me how to achieve this.
var astname = "Laptop";
Asset.find({ astname : astname}, function(err, foundcategory){
if(err){
console.log(err);
} else {
console.log(foundcategory.category);
}
})
foundcategory is an array in your example. Use findOne instead of find to query for a single document.
var astname = "Laptop";
Asset.findOne({ astname : astname}, function(err, foundcategory){
if(err){
console.log(err);
} else {
console.log(foundcategory.category);
}
})

Mongoose middleware access other collection

I am using 'pre' 'save' middleware to create for a 'user' document a corresponding 'userObjects' document.
So there is users collections and userObjects.
And when new user is inserted a userObjects document should be inserted too.
I am trying to use the 'pre' middleware, somehow like this :
//before inserting a new user
Users.pre('save', function(next) {
var UserObjects = db.model('userObjects');
userObjectsIns = new UserObjects({
'userID': this._id,
'myObjects':[],
});
userObjectsIns.save( function(err) {
if (err) console.log("ERROR while saving userObjectsIns: " + err);
next()
})
});
The obvious problem, is that db doesn't exists. How can I reach 'userObjects' collection from within this pre middleware?
You can access other models via the model method of the this doc instance:
Users.pre('save', function(next) {
var UserObjects = this.model('userObjects');
userObjectsIns = new UserObjects({
'userID': this._id,
'myObjects':[],
});
userObjectsIns.save( function(err) {
if (err) console.log("ERROR while saving userObjectsIns: " + err);
next()
})
});

Node.js mongodb update over ObjectID

I want to update my Document but it's not working 100% .
// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/testDB", function(err, database) { //"mongodb://localhost:27017/test"
if(err) throw err;
db = database;
});
My collection row looks like:
{ "_id" : ObjectId("53f9379ce9575bbe9ec29581"), "name:paco",
"status:student" }
Now if I want to update the row over the Document as follows:
db.collection('user', function(err, collection){
collection.update({'_id':ObjectID(req.session.loggedIn)}, {image : filename}, {w:1}, function(err, result){
console.log(result);
I am getting just:
{ "_id" : ObjectId("53f9379ce9575bbe9ec29581"), "image:filename" }
How can I make an update to get my data like this??:
{ "_id" : ObjectId("53f9379ce9575bbe9ec29581"), "name:paco",
"status:student" , "image:filename"}
Doing an update the way you did it is going to retrieve the document in your collection with the specified _id, then it is going to replace the content of this document with what you specified as your second parameter. In your case, it will retrieve the document with _id 53f9379ce9575bbe9ec29581, and replace the existing fields with the field you passed, image:filename (that means the existing fields will be removed, as you noticed).
What you want to do is use the $set operator. This operator will not touch the document retrieved, but only modify the field that you specified, or add it if it does not exist.
So your update command should look something like this:
db.collection('user').update({'_id':ObjectID(req.session.loggedIn)}, {$set: {image : filename}}, {w:1}, function(err, result){
console.log(result);
to update record by _id
var ObjectID = require('mongodb').ObjectID;
exports.updateUser = function(req, res) {
var collection = db.collection('users');
collection.update(where, $set:req.body, function(err, result) {
if (err) {
console.log('Error updating user: ' + err);
res.send({'error':'An error has occurred'});
} else {
console.log('' + result + ' document(s) updated');
res.send(user);
}
});
}

Pre-populating documents using Mongoose + Express

I am new to Node+Mongoose, and am currently in the process of creating an API using KeystoneJS. I've managed to populate all posts with the author's email and name. My question is, is there a way to populate the post with author everytime, possibly with some middlewear, without having to rewrite it in each method where I retrieve posts? My goal is to not have multiple instances of populate('author', 'email name') scattered throughout the code. For instance, in the future, I'd like to include the author's profile photo url as well, and I'd prefer to be able to make that change in a single place, that will then be reflected in every place that I retrieve posts.
Current implementation:
Post.model.find().populate('author', 'email name').exec(function (err, posts) {
if (!err) {
return res.json(posts);
} else {
return res.status(500).send("Error:<br><br>" + JSON.stringify(err));
}
});
Post.model.findById(req.params.id).populate('author', 'email name').exec(function (err, post) {
if(!err) {
if (post) {
return res.json(post);
} else {
return res.json({ error: 'Not found' });
}
} else {
return res.status(500).send("Error:<br><br>" + JSON.stringify(err));
}
});
You can create model using statics. This is example of methods for schema
PostSchema.statics = {
getAll: function(cb) {
return this
.find()
.populate('author', 'email name')
.exec(cb);
}
}
You still should use "populate", but it will be in schema file, so you will not care about it in future

Resources