我在嘗試在對象數組內保存數組時遇到了一些麻煩。貓鼬:'投射到嵌入路徑失敗的值。無法使用'in'運算符搜索'_id'
我從服務器獲取以下回應:
{ [CastError: Cast to embedded failed for value "\'maxbeds: 4\'" at path "saved_searches"]
message: 'Cast to embedded failed for value "\\\'maxbeds: 4\\\'" at path "saved_searches"',
name: 'CastError',
kind: 'embedded',
value: '\'maxbeds: 4\'',
path: 'saved_searches',
reason: [TypeError: Cannot use 'in' operator to search for '_id' in maxbeds: 4] }
這裏是我的架構:
var mongoose = require('mongoose'),
rfr = require('rfr'),
passwordHelper = rfr('server/helpers/password.js'),
Schema = mongoose.Schema,
_ = require('lodash');
/*
*
* Creating UserSchema for MongoDB
*
*/
var UserSchema = new Schema({
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true,
select: false
},
name: {
type: String,
required: true
},
passwordSalt: {
type: String,
required: true,
select: false
},
saved_houses: [{
mlsId: {
type: String
},
addressFull: {
type: String
},
bedrooms: {
type: Number
},
listPrice: {
type: Number
},
bathrooms: {
type: Number
},
sqft: {
type: Number
},
createdAt: {
type: Date,
default: Date.now
}
}],
saved_searches: [{
search_name: {
type: String
},
filters: {
type: [Schema.Types.Mixed]
},
createdAt: {
type: Date,
default: Date.now
}
}],
active: {
type: Boolean,
default: true
},
createdAt: {
type: Date,
default: Date.now
}
});
// compile User model
module.exports = mongoose.model('User', UserSchema);
的問題,我認爲這是濾波器陣列住saved_searches內的物體內array
現在,在我的路由器中,我執行以下操作:
var express = require('express'),
savedDataRouter = express.Router(),
mongoose = require('mongoose'),
rfr = require('rfr'),
s = rfr('server/routes/config/jwt_config.js'),
User = rfr('server/models/User.js'),
jwt = require('jsonwebtoken');
savedDataRouter.post('/searches', function (req, res) {
if (mongoose.Types.ObjectId.isValid(req.body.userId)) {
User.findByIdAndUpdate({
_id: req.body.userId
}, {
$push: {
saved_searches: {
search_name: req.body.search_name,
$each: req.body.filters
}
},
}, {
new: true
},
function (err, doc) {
if (err || !doc) {
console.log(err);
res.json({
status: 400,
message: "Unable to save search." + err
});
} else {
return res.json(doc);
}
});
} else {
return res.status(404).json({
message: "Unable to find user"
});
}
});
如果我登錄請求主體來自客戶端,我得到以下幾點:
//console.log(req.body)
{ search_name: 'Sarasota',
filters: [ 'minbaths: 1', 'maxbaths: 3', 'minbeds: 2', 'maxbeds: 4' ],
userId: '583359409a1e0167d1a3a2b3' }
我已經嘗試了所有我見過的StackOverflow和其他在線資源,沒有運氣的事。希望有人能指引我正確的方向或告訴我我做錯了什麼。
我真的很感激任何幫助,你可以給我同行的代碼。
編輯
添加模塊依賴於我的UserSchema和SavedDataRouter
你可以什麼是你想實現闡述。什麼應該是正確的saved_search對象? –
@Gurbakhshish Singh well Im基本上試圖傳遞2個參數:search_name,它是一個字符串,它是一個字符串數組。我想要做的是讓我的數據庫查找正確的用戶並將此信息嵌入名爲saved_searches的對象數組中。這樣一個成功的帖子看起來像saved_searches:{search_name:'some string',filters:[array_of_strings]} –