Я пытаюсь добавить свой googleID (объект) на карту в другой схеме Мангуста. Я преобразую в строку свой объект идентификатора пользователя, и во время моего тестового кода я получаю эту ошибку:
(node:293528) UnhandledPromiseRejectionWarning: ValidationError: collection validation failed: likes.5dbf6205bdcd5e5f78536447: Cast to ObjectId failed for value "110840542851551561690" at path "likes.$*"
at new ValidationError (C:\files\node_modules\mongoose\lib\error\validation.js:30:11)
at model.Document.invalidate (C:\files\node_modules\mongoose\lib\document.js:2333:32)
at Map.set (C:\files\node_modules\mongoose\lib\types\map.js:71:26)
at C:\files\app.js:123:30
at C:\files\node_modules\mongoose\lib\model.js:4589:16
at C:\files\node_modules\mongoose\lib\query.js:4323:12
at process.nextTick (C:\files\node_modules\mongoose\lib\query.js:2805:28)
at process._tickCallback (internal/process/next_tick.js:61:11)
(node:293528) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:293528) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Мой пост запрос от client.js:
const likesForm = document.getElementById("test");
likesForm.addEventListener("submit", function (evt) {
evt.preventDefault();
console.log(event.target.id)
const [likeString, itemId] = evt.target.id.split("-");
vote(
likeString === "like"
? "1"
: "-1",
itemId
);
}, false);
async function vote (voteInc, itemId) {
const route = `/like/${itemId}`;
const response = await fetch(route, {
method: 'POST',
body: JSON.stringify({"like": voteInc}),
headers: {
'Content-Type': 'application/json'
}
});
const result = await response.json();
console.log(result);
}
Сообщение на стороне сервера:
app.post("/like/:id",(req,res)=>{
const id = req.params.id;
const like = req.body.like;
console.log(like);
console.log(id);
if(req.isAuthenticated()){
linkscr.user.findById(req.user.id, (e,foundUser)=>{
if(e){
console.log(e);
}else{
//if like = 1
if(like==1){
linkscr.collection.findById(id, function(error,result){
if(error){
console.log(error);
}else{
result.likes.set(foundUser._id.toString(),foundUser.googleId);
result.save();
}
})
console.log("not voted yet. Add 1 and added to like");
}else{
linkscr.collection.findById(id, function(error,result){
if(error){
console.log(error);
}else{
result.dislikes.set(foundUser._id.toString(),foundUser.googleId);
result.save();
}
})
console.log("not voted yet. Add 1 and added to dislike");
};
};
});
}else{
res.redirect("/");
}
});
Моя любимая / неприязненная схема:
likes : {
type: Map,
of: {
type: mongoose.Schema.Types.ObjectId,
ref: "User" }
},
dislikes : {
type: Map,
of: {
type: mongoose.Schema.Types.ObjectId,
ref: "User" }
},
Как схема изначально сохраняется:
likes : {[User._id]:User},
dislikes : {},
Спасибо за любую помощь. Ты моя единственная надежда, стек!
Сначала я подумал, что это проблема Мангуста, как я относился к своим объектам, но похоже, что это больше связано с асинхронными вещами. По общему признанию это - моя самая большая слабость в программировании в то время, когда я писал это.
РЕДАКТИРОВАТЬ: Из того, что я смотрю из документации, Мангуст не может устанавливать объекты только строки. Монго не может мангуст.
Редактировать 2: Мой плохой, я поставил неправильный идентификатор в неправильном месте. foundUser._id.toString() ,foundUser