我的架構如下圖所示:多paramters貓鼬findOne不起作用
itemLike.findOne({ 'item_id': itemData.item_id, 'user': userInfo }).then((info) => {
if (!info) {
let newItem = new itemLike();
newItem.no_of_likes = 1;
newItem.users.push(userInfo);
newItem.save().then((likeInfo) => {
res.json({
status: '200',
message: 'Thanks for appreciating our product',
data: likeInfo
});
}).catch((err) => {
console.log("hh " + err);
res.json({
status: '500',
message: 'Oops,something went wrong'
});
});
} else {
res.json({
status: '200',
message: 'you have already liked the product'
});
}
}).catch((err) => {
console.log("ll " + err);
res.json({
status: '500',
message: 'Oops,something went wrong'
});
});
這裏假設我的迴應:如下圖所示
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const itemLike = new Schema({
item_id: { type: mongoose.Schema.ObjectId, ref: 'items', index: true },
no_of_likes: { type: Number, default: 0 },
users: [{ type: mongoose.Schema.ObjectId, ref: 'user' }]
}, { versionKey: false });
module.exports = mongoose.model('item_like', itemLike);
我查詢
itemLike.js
如下所示:{
"status": "200",
"message": "Thanks for appreciating our product",
"data": {
"_id": "5990dd8e669a041fec3aecb9",
"users": [
"591325c6b685bc165313a8ff",
"591325c6b685bc165313a8ef"
],
"no_of_likes": 1
}
}
現在假設當我把item_id: 5990dd8e669a041fec3aecb9
和users:591325c6b685bc165313a8ef
findOne查詢,它應該給我的確切文件。但對於這種情況findOne無法找到documet,我認爲users
字段是一個ref-array,它不能同時查看這兩個參數。那麼我怎樣才能實現這個功能呢?
它應該是'users',而不是'user'(單個)。 – alexmac
是的,我改變了'用戶',但問題仍然存在。爲此,我更新了我的問題 –