Filling a form (caolan) with default values in node.js - forms

I am using caolan forms with node.js. My schema looks like:
var News = new Schema({
name : String
, index: Number
});
My form has 3 news fields:
var news = forms.create({ news_1: fields.string({required: true}),
news_2: fields.string({required: true}),
news_3: fields.string({required: true})
});
I now try to fill this form with default values which is where I need help. What am I doing wrong in the following code?
news.bind({news_1: "test1", news_2: "test2", news_3: "test3"});
Thanks.

You can create form with this object
{
news_1: fields.string({required: true, value : 'test1'}),
news_2: fields.string({required: true, value : 'test2'}),
news_3: fields.string({required: true, value : 'test3'})
}

Related

Create multiple documents from an array of values in Mongo DB

I'm new to MongoDB and I know this might sound silly to many but is there a way(s) where you can create multiple documents from an array of values. I have written some code for this, but is there any other efficient/shorter way of doing that.
tags.map(async tag => {
const tagDoc = await TagModel.create({ tag, postID })
})
Tag Schema -
const tagSchema = new mongoose.Schema({
postID: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Post",
}],
tag: {
type: String,
required: true,
},
}, { timestamps: true })
Case 1 : Storing Tags in Same Collection
in mysql you have to store tags in different table , but in mongodb you can use same collection to store tags as array of string
in your post schema :
const postSchema = new mongoose.Schema({
...
tags: {
type: [String],
required: true,
}
});
when saving post =>
let post = new Post();
...
post.tags = req.body.tags; // ["Tag1","hello","Testing"];
await post.save();
Case 2 : Storing Tags in Different Collection
if you want to store tags in different collection Tag , then you can use Mongoose InsertMany()
let tags = req.body.tags ; // ["Tag1","hello","Testing"];
tagsArray = tags.map((t)=> { return {postID:post._id , tag:t}});
let tagsSaved = await Tag.insertMany(tagsArray);
console.log('tagsSaved=',tagsSaved);

Express.js PUT Request not updating MongoDB

I'm working on a project that is basically a super watered down social media website.
I have a chunk done already, but I'm having some issues creating a put request to my mongodb. Basically, I want to send a put request to update a numeric value to be able to have a like counter on each post.
What I'm trying do here is send a put request with a specific post id. I'm storing the post id in a hidden text box to reference it. This is pug formatted HTML:
input.form-control(type='hidden' value=item.id id='postId' placeholder='' name='postId' required='false')
form(method='PUT' action='/update/{{post._id}}')
button(type='submit') Like
Then in my router.js file I'm basically trying to take in that id and set the likes field in the Post schema to 1 (just for testing).
router.put('/update/:id', function (req, res, next) {
let id = {
_id: ObjectID(req.params.id)
};
Post.update({_id: id}, {$set:{'likes': 1}}, (err, result) => {
if(err) {
throw err;
}
res.send('user updated sucessfully');
});
});
Here is my post schema
var mongoose = require("mongoose");
var PostSchema = new mongoose.Schema({
postText: {
type: String,
unique: false,
required: true,
trim: true
},
usernameText: {
type: String,
unique: false,
required: true,
trim: true
},
likes:{
type: Number,
unique: false,
required: false
}
});
var Post = mongoose.model("Posts", PostSchema);
module.exports = Post;
Any and all help would be highly appreciated, thank you
You can't change the ObjectId. The ObjectId is generated by MongoDB and can't be changed by the user using query functions.
If you want to assign a unique id to each user for example, then create a separate field in your schema.
You cannot change the ID
'PUT' method is not supported directly as far as I know. You need method override

How to set a default collection in mongoose embedded document schema

How can I set a default collection in a model schema in mongoose. Using the basic example, how can I have for example a default comment in the comments array. e.g.
var defaultComment = {title: 'add your first post'}
do I do something like this in the definition? comments: {type:[Comments], default:defaultComment }
var Comments = new Schema({
title : String
, body : String
, date : Date
});
var BlogPost = new Schema({
author : ObjectId
, title : String
, body : String
, date : Date
, comments : [Comments]
, meta : {
votes : Number
, favs : Number
}
});
mongoose.model('BlogPost', BlogPost);
According to the Mongoose documentation for Schemas, keys may specify a default value. So for your example, one might define the Comments schema as so:
var Comments = new Schema({
title : String
, body : String
, date : Date
});
var CommentsModel = mongoose.model("comments", Comments);
Then, store your default comment, and use it as the default value in your BlogPost schema:
var defaultComment = new CommentsModel({
title: "Add your first post"
});
var BlogPost = new Schema({
author : ObjectId
, title : String
, body : String
, date : Date
, comments : { type: [Comments], default: defaultComment }
, meta : {
votes : Number
, favs : Number
}
});
I hope this helps. Cheers!

Why does MongoDB increase _id by one when inserting with custom id value

I am having some weird issue when inserting a new document with a custom _id value. If i insert a document with a custom _id of 1020716632230383 it gets saved in the database as 1020716632230384. For some reason it is incremented by 1.
what may cause this?
My query is :
exports.register = function(req, res){
console.log('ATTEMPT to register a user with id: ' + req.body.userInfo.id);
// prints 1020716632230383 !!!
var query = {'_id': req.body.userInfo.id};
var update = {
'_id': req.body.userInfo.id ,
'name': req.body.userInfo.name
};
var options = {
upsert: true,
setDefaultsOnInsert : true
};
User.findOneAndUpdate(query, update, options).exec(function(err ,doc){
if(!err){
console.log('REGISTERED!: ' , doc);
res.status(200).json({'success': true, 'doc': doc});
}else{
console.log(err);
res.status(200).json({'success': false});
}
});
};
In my Schema the _id is defined to be a number.
_id: {type:Number}
it is because "setDefaultsOnInsert : true" . when you use this option you can't update "_id" field. it is setting by mongoose.
if you want have a custom "_id" be sure "setDefaultsOnInsert" option is "false".
it is one of problems in mongoose .

Mongodb, getting the id of the newly pushed embedded object

I have embedded comments in a posts model. I am using mongoosejs. After pushing a new comment in a post, I want to access the id of the newly added embedded comment. Not sure how to get it.
Here is how the code looks like.
var post = Post.findById(postId,function(err,post){
if(err){console.log(err);self.res.send(500,err)}
post.comments.push(comment);
post.save(function(err,story){
if(err){console.log(err);self.res.send(500,err)}
self.res.send(comment);
})
});
In the above code, the id of the comment is not returned. Note there is a _id field which is created in the db.
The schema looks like
var CommentSchema = new Schema({
...
})
var PostSchema = new Schema({
...
comments:[CommentSchema],
...
});
A document's _id value is actually assigned by the client, not the server. So the _id of the new comment is available right after you call:
post.comments.push(comment);
The embedded doc pushed to post.comments will have its _id assigned as it's added, so you can pull it from there:
console.log('_id assigned is: %s', post.comments[post.comments.length-1]._id);
You can manually generate the _id then you don't have to worry about pulling it back out later.
var mongoose = require('mongoose');
var myId = mongoose.Types.ObjectId();
// then set the _id key manually in your object
_id: myId
// or
myObject[_id] = myId
// then you can use it wherever
_id field is generated at client side, you can get the id of the embedded document by comment.id
sample
> var CommentSchema = new Schema({
text:{type:String}
})
> var CommentSchema = new mongoose.Schema({
text:{type:String}
})
> var Story = db.model('story',StorySchema)
> var Comment = db.model('comment',CommentSchema)
> s= new Story({title:1111})
{ title: '1111', _id: 5093c6523f0446990e000003, comments: [] }
> c= new Comment({text:'hi'})
{ text: 'hi', _id: 5093c65e3f0446990e000004 }
> s.comments.push(c)
> s.save()
verify in mongo db shell
> db.stories.findOne()
{
"title" : "1111",
"_id" : ObjectId("5093c6523f0446990e000003"),
"comments" : [
{
"_id" : ObjectId("5093c65e3f0446990e000004"),
"text" : "hi"
}
],
"__v" : 0
}