How to store data inside mongodb - mongodb

js and mongodb.I have created a model file named models like the one given below
User = new Schema({
username : String
, password : String
, created_at : Date
});
mongoose.model('User', User);
exports.defineModels = defineModels;
In app.js i have called the defineModels like this:
var models = require('./models'),
models.defineModels(mongoose, function() {
app.User = User = mongoose.model('User');
db = mongoose.connect(app.set('db-uri'));
})
I can't call save method directly on User or can I?
i want to save data in User what could be the function for the same.any answer will be appriciated

To do what you want, you should have something like this:
var user = new User({username: 'Name', password: 'unsecure'});
user.save();
There are a few things odd with your code, so I highly suggest going over a tutorial that uses express and mongoose to create a sample site (most likely you can find a blog).
Here is one I made: https://github.com/mathrawka/node-express-starter
Good luck!

Related

how to get data from existing mongo collection using parse server?

I am new to Parse Server.
I am having an existing collection "users" in "employee" db in Mongodb.
I need to get the users data using Parse Server.
Below is the code:
var query = new Parse.Query(users);
query.find().then((data) => {
return data;
}).catch((error) => {
return error;
});
But I am getting the error "users" is not defined.
Need some valuable help.
if your Class really is called users (which is different to the built-in Parse Server Class called User), then use :
var query = new Parse.Query('users'); //note the quotation around 'users'
If you are in fact trying to query the built-in User class, use :
var query = new Parse.Query(Parse.User);
or
var query = new Parse.Query('_User');

Firestore .set not saving data from firebase cloud function

I am trying to save data from my form in firestore. The collection users already exists and the document 'email' also exists already. It's not saving and nor does it give any error or messages.
Any ideas why that would happen? I am able to save data from another page though. I copied the same const admin = require('firebase-admin');
and
const db = admin.firestore();
to this page as well, exactly same. Not working:
let setDoc = db
.collection('users')
.doc(email)
.set({'abc':'def'},{merge: true});
// .set(Encdata,{merge: true})
return setDoc.then(res => {
console.log('Set: ', res);
})
.catch(error => {
console.log(error);
});
Working from another page:
let setA = docRef.set({
'username': encDec.encrypt(user_name),
'password' : encDec.encrypt(password),
'email': email,
'uid': UserID
});```
Before and After I trigger the function, data remains the same. All instructions in the function execute fine UNTIL the control reaches the "let setDoc = db" line. After that everything just silently quits.
From your description and codes, it seems you intended to overwrite a single document. Based on the Add data to Cloud Firestore documentation set a documentation to overwrite a single one, the first set method fit for the situation.
Finally I figured this one out. Maybe because too much of screen time, but basically I was messing up the init statement
instead of
db = admin.firestore();
I had the statement:
db = admin.database();
==> this was messing up all my references to db.
So db.collection().get() was not working.
Thanks to all who answered.
Hope this helps someone.

Backbonejs Model.url required?

I have an example setup to show my issue: http://jsfiddle.net/5xo4yzw2/1/
var root = "http://jsonplaceholder.typicode.com"
var Post = Backbone.Model.extend({
url: function(){
return this.get('url') || root + "/posts/" + this.get('id')
}
});
var Posts = Backbone.Collection.extend({
model: Post,
url: root + "/posts"
});
var posts = new Posts();
posts.fetch();
console.log("Call to collection fetch works")
var post = new Post({id: 1});
post.fetch();
console.log("Call to collection fetch works")
This example works, that is, both of the console.logs are executed without an exception being raised by .fetch(). It was my understanding, however, from both http://backbonejs.org/#Model-url and the book I am reading, that once I specify "/posts" as the collection url, the model url should be automatically resolved to [collection.url]/[id], though that is not the case. If I do not provide the url function in the model, an exception is raises upon fetching, stating the th url parameter must be provided.
Have i misunderstood something?
You haven't added your post model to your collection, in order for a model to use the collections URL it must be part of that collection.
For example
var post = new Post({id: 1});
posts.add(post);
post.fetch();
console.log("Call to collection fetch works")
Updated Fiddle
As #Artem Baranovskii pointed out, If you want to use a model outside a collection you should be using the urlRoot property. From the documentation
Specify a urlRoot if you're using a model outside of a collection, to
enable the default url function to generate URLs based on the model
id. "[urlRoot]/id" Normally, you won't need to define this. Note that
urlRoot may also be a function.
If you're using a model outside of the collection you could use urlRoot like the following:
var root = "http://jsonplaceholder.typicode.com"
var Posts = Backbone.Model.extend({
urlRoot: function () {
return this.get('url') || (root + "/posts/" + this.get('id'))
}
});
var posts = new Posts();
posts.fetch();
console.log("Call to collection fetch works")
When you execute fetch the model tries to get url by the several approaches here

Mongoose - Restrict the fields on referenced model

I have users model that can hold multiple notifications. In the NotificationSchema the notifier holds users ID and it references the users model. When I execute the following query :
User.find().populate('notifications.notifier').exec(function(err,users){
//users[0].notifications[0].notifier
//I am getting all fields from the referenced user
//I don't want the whole document but some fields only
});
How can someone Limit / Restrict the fields that should be available while referencing to some model.
Here is the users model
var NotificationSchema =new Schema({
notifier : {type:Schema.Types.ObjectId, ref:'users'},
//How could I say :
//notifier : {type:Schema.Types.ObjectId, ref:'users', fields:['_id', 'name']}
//because I know what fields do I need from referenced model for this Schema.
__SOME__
__OTHER__
__FIELDS__
});
var UsersSchema = new Schema({
name : {given:String, middle:String, family:String}
email:String,
password:String,
notifications : [NotificationSchema]
});
var Users = mongoose.model('users', UsersSchema);
BTW, I do not have separate model for NotificationSchema.
If this feature is not available out of the box how could I implement it manually. Am I missing some docs? Please let me know the robust way of doing it.
I found it in mongoose docs
I found the answer in Field Selection Section of the documentation
User.find().populate('notifications.notifier', '_id name').exec(function(err, users) {
//users[0].notifications[0].notifier ^^^^^^^^^ HOW FUNNY
//Yes I am getting '_id' and 'name' fileds only
});

Node + Mongoose: Get last inserted ID?

I want to retrieve the last inserted _id, using mongoose as MongoDB wrapper for node.js. I've found the following tutorial, but I can't change any node modules because the app runs on a public server:
Getting "Last Inserted ID" (hint - you have to hack Mongoose)
Any other ideas? This what I want to do:
Insert new user
Get user's _id value
Set a new session based on user's id
Redirect to /
Thanks!
I'm using mongoose version 1.2.0 and as soon as I created a new instance of a mongoose model, the _id is already set.
coffee> u = new User()
[object Object]
coffee> u._id
4dd68fc449aaedd177000001
I also verified that after I call u.save() the _id remains the same. I verified via MongoHub that this is indeed the real ID saved into MongoDB.
If you explicitly declare
_id: Schema.ObjectId
for your model, then the ObjectId will not be available after new or save.
This is probably a bug.
If you're looking to get the last inserted _id of a sub object, then create the object, and add it to the item. Here's an example in NowJS using MongoDB and Mongoose (to add some schema sugar) which then converts the result to JSON to send back to the client:
var nowRoomID = this.now.room;
var Conversation = mongoose.model('Conversation');
Conversation.findById(convID, function(error, conversation) {
var Blip = mongoose.model('Blip');
var createdBlip = new Blip();
createdBlip.author= nowUserName;
createdBlip.authorid = parsed.authorid;
createdBlip.body = revisedText;
createdBlip.created_at = new Date();
createdBlip.modified_at = new Date();
conversation.blips.push(createdBlip);
parsed._id = createdBlip._id; //NOTE: ID ACCESSED HERE
message = JSON.stringify(parsed);
conversation.save(function (err) {
if (!err) {
console.log('Success - saved a blip onto a conversation!');
nowjs.getGroup(nowRoomID).now.receiveMessage(nowUserName, message);
}
});
With MongoDB, if you don't explicitly set a document's _id value then the client driver will automatically set it to an ObjectId value. This is different from databases that might generate IDs on the server and need another query to retrieve it, like with SQL Server's scope_identity() or MySQL's last_insert_id().
This allows you to insert data asynchronously because don't need to wait for the server to return an _id value before you continue.
So, as shown is Peter's answer, the _id is available before the document is saved to the database.
I just get the id from the document passed to the callback, since save returns the saved document.
Check below url
http://mongodb.github.io/node-mongodb-native/markdown-docs/insert.html
you will find following code in given url
var document = {name:"David", title:"About MongoDB"};
collection.insert(document, {w: 1}, function(err, records){
console.log("Record added as "+records[0]._id);
});