I am saving fields from a form into a mongo db collection using formidable.
the schema for the model ENTRY is this.
const mongoose=require('mongoose');
const entrySchema = mongoose.Schema({
product:{
name:{
type:String,
required:true
},
image:{
type:String
},
// document:{
// type:
// },
description:{
type:String
}
},
brand:{
name:{
type:String
},
logo:{
type:String
}
},
organisation:{
name:{
type:String
},
logo:{
type:String
},
phone:{
type:String
},
mobile:{
type:String
},
email : {
type:String
}
},
category:{
type : Object
}
},
{
collection : "entries"
}
)
const Entries = mongoose.model('entry', entrySchema)
module.exports = Entries;
now the CATEGORY field is a an OBJECT type and and I want to add an object from another collection called CATEGORIES. I will be able to findById and I want to insert it into the new document that is being saved on submission of the form.
I am trying to do this by
entry.category=Categories.findById({_id:fields.categoryId});
It's not working.. I seem to be gettind this error although I don't know if it's related to the above or something else
Error: key xxxx-shard-00-00.p5yeb.mongodb.net:27017 must not contain '.'
at serializeInto (/Applications/MAMP/htdocs/xxxx-server/node_modules/bson/lib/bson/parser/serializer.js:816:19)
at serializeObject (/Applications/MAMP/htdocs/xxxx-server/node_modules/bson/lib/bson/parser/serializer.js:347:18)
at serializeInto (/Applications/MAMP/htdocs/xxxx-server/node_modules/bson/lib/bson/parser/serializer.js:947:17)
Could anyone advise me on how I can manage this?
Here you are using findById
so you only need to pass the id value instead of object:
Can you try this:
entry.category = await Categories.findById(fields.categoryId).exec();
Still, if you want to use the object you can use findOne
entry.category = await Categories.findOne({ _id: fields.categoryId}).exec();
You can check this documentation on findById, findOne and Promises