我有两个模型,贸易和工作,作为劳动的类别和子类别。我想要新添加的内容根据给定的工作自动选择交易,但我似乎无法找到包含工作ID的交易:
labor.server.model.js:
const WorkSchema = new Schema({
WORK_NAME: String
}, {
autoIndex: false
});
const TradeSchema = new Schema({
TRADE_NAME: String,
WORKS: [WorkSchema]
}, {
autoIndex: false
});
api.server.controller.js:
exports.addlabor = function(req, res, next) {
var Labor = mongoose.model('Labor');
var Trade = mongoose.model('Trade');
if (!req.body.CATEGORY) {
Trade
.find({WORKS: [req.body.SUBCATEGORY]}) // SOMETHING LIKE THIS?
.exec(function(err, data) {
if (err) {
console.log(err);
} else {
req.body.CATEGORY = data._id;
}
});
}
const labor = new Labor(req.body);
labor.save((err) => {
if (err) {
console.log(err);
}
res.redirect('/labor');
});
};
答案 0 :(得分:1)
您可以尝试以下
var work = 'painting' //req.body.SUBCATEGORY string
//change to find to get all matching
Trade.findOne( { 'WORKS.WORK_NAME' : work }, function( err,doc ){
if(err) throw err;
console.log(doc);
})
控制台
saravana@ubuntu:~/node-mongoose$ node so4.js
`open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/connections.html#use-mongo-client
Mongoose: trades.findOne({ 'WORKS.WORK_NAME': 'painting' }, { fields: {} })
{ _id: 5a5d6b50d1c8c30ade0c3d4c,
TRADE_NAME: 'painter',
__v: 0,
WORKS: [ { WORK_NAME: 'painting', _id: 5a5d6b50d1c8c30ade0c3d4d } ] }
^C
saravana@ubuntu:~/node-mongoose$