I'm trying to write a JS app with MongoDB (I use MongoDB Compass). I have a schema of user:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: {
type: String,
minlength: 2,
maxlength: 30,
required: true,
},
about: {
type: String,
minlength: 2,
maxlength: 30,
required: true,
}
});
Then I import some data from JSON file like this:
[
{
"name": "Ada Lovelace",
"about": "Mathematician, writer",
"_id": "dbfe53c3c4d568240378b0c6"
}
]
After the importing the type of field _id is String. But, if I create a user by method create:
const createUser = (req, res) => {
const { name, about } = req.body;
User.create({ name, about })
.then((user) => res.status(200).send({ data: user }))
.catch((err) => {
if (err.name === 'ValidationError') {
return res.status(400).send({ message: `Wrong value: ${err}` });
}
return res.status(500).send({ message: `Server error: ${err}` });
});
};
the type of _id is ObjectId, therefore, I can't use methods like User.findByIdAndUpdate
, User.findByIdAndRemove
etc on the same data, these methods work only with ObjectId type.
question from:
https://stackoverflow.com/questions/65868915/different-types-of-the-field-id-of-rows-after-importing-data-to-mongodb-and-aft 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…