如何更新多个字段,包括推入 NodeJs mongoose 中的现有数组?
How to Update multiple field including push into an existing array in NodeJs mongoose?
这是我在 nodeJs 中使用 mongoose 的产品架构。但是我正在开发 REST API。
const ImageSchema = new Schema({
path: {
type: String
},
pos: {
type: Number
}
});
const ProductSchema = new Schema({
title: {
type: String,
required: [true, 'Product title is required.']
},
description: {
type: String
},
created_date: {
type: Date ,
required: [true, 'Created Time required.'],
default: Date.now
},
images: [
ImageSchema
]
});
const Product = mongoose.model('product', ProductSchema);
module.exports = Product;
这是我更新产品的方式
router.put('/:id', upload.single('pImg'), function(req, res, next){
var x = req.body;
Product.findByIdAndUpdate({
_id: req.params.id
}, x).then(function(){
Product.findOne({
_id: req.params.id
}).then(function(product){
res.send(product);
});
}).catch(next);
});
我的问题是如何在推入图像数组的同时更新标题、描述等其他字段?
您可以在通话中使用 $push 和 $set。
这是我在 nodeJs 中使用 mongoose 的产品架构。但是我正在开发 REST API。
const ImageSchema = new Schema({
path: {
type: String
},
pos: {
type: Number
}
});
const ProductSchema = new Schema({
title: {
type: String,
required: [true, 'Product title is required.']
},
description: {
type: String
},
created_date: {
type: Date ,
required: [true, 'Created Time required.'],
default: Date.now
},
images: [
ImageSchema
]
});
const Product = mongoose.model('product', ProductSchema);
module.exports = Product;
这是我更新产品的方式
router.put('/:id', upload.single('pImg'), function(req, res, next){
var x = req.body;
Product.findByIdAndUpdate({
_id: req.params.id
}, x).then(function(){
Product.findOne({
_id: req.params.id
}).then(function(product){
res.send(product);
});
}).catch(next);
});
我的问题是如何在推入图像数组的同时更新标题、描述等其他字段?
您可以在通话中使用 $push 和 $set。