I am using MongoDB + Node.js to create an app, but I am receiving an error for this code:
company.js
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var companySchema = Schema({ creator: { type: Schema.Types.ObjectId, ref: 'User' }, name: String, description: String, categories: [String], website: String, address: String, statuses: [{ date: { type: Date, default: Date.now }, status: String }], friends: [{ name: String, description: String }], priority: Number, isActive: Boolean, contacts: [{ type: Schema.Types.ObjectId, ref: 'ContactPerson' }], createdOn: { type: Date, default: Date.now } }); module.exports = mongoose.model('Company', companySchema);
api.js
api.route('/company') .post(function(req, res) { var company = new Company({ creator: req.decoded.id, name: req.body.name, description: req.body.description, categories: req.body.categories, website: req.body.website, address: req.body.address, friends.name: req.body.friendName, statuses: { status: "New Company" }, priority: req.body.priority, }); company.save(function(err, newCompany) { if(err) { res.send(err); return } res.json({ message: "New company has been created!" }); }); })
Error
friends.name: req.body.friendName,
SyntaxError: Unexpected token .
I also tried with friend[‘name’] but the result was the same: SyntaxError: Unexpected token [
Please tell me where is my mistake
Advertisement
Answer
Try:
var company = new Company({ creator: req.decoded.id, name: req.body.name, description: req.body.description, categories: req.body.categories, website: req.body.website, address: req.body.address, friends: { name: req.body.friendName }, statuses: { status: "New Company" }, priority: req.body.priority, });
or:
var company = new Company({ creator: req.decoded.id, name: req.body.name, description: req.body.description, categories: req.body.categories, website: req.body.website, address: req.body.address, 'friends.name': req.body.friendName, statuses: { status: "New Company" }, priority: req.body.priority, });
depend on what you’re after.