2
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
    name: String,
    created: new Date()
})

const user = mongoose.model('user', userSchema);

module.exports = user;

After adding new Date() I get an error saying : TypeError: Undefined type undefined at created Did you try nesting Schemas? You can only nest using refs or arrays.

2 Answers 2

3

You are defining schema and you just need a type there not the object. Instead of using new Date() just use Date.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
    name: String,
    created: Date
})

const user = mongoose.model('user', userSchema);

module.exports = user;
0

I would guess that your intention was to have a Date field type with a mongoose default value of the current date time ... since you named that field created. I would go a step further and name it created_At ...

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
    name: String,
    created_At: { type: Date, default: Date.now }
})

const user = mongoose.model('user', userSchema);

module.exports = user;

Now you will have an auto filled created_At Date field every time you create a new user model.

We specifically said what type we want the field to be and we also added a default value.

You can read more about mongoose defaults here

2
  • app.put('/users/:id', (req,res) => { Users.findOneAndUpdate({_id: req.params.id}, { $set:{ name: req.body.name, created_At: req.params.created_At }, function(err, result){ if(err){ res.json(err) }else{ res.json({'result': 'ok'}) } } }) }) I tried updating it like but it's not working. What am I doing wrong?
    – kathmandu
    Oct 6, 2018 at 0:07
  • you get an error or? What is the value of req.params.created_At?
    – Akrion
    Oct 6, 2018 at 0:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.