我正在尝试使用express框架在nodejs中的db中的集合中的所有现有文档中插入子文档。以下是代码片段:
updatedoc: function(update,options,cb)
{
return this.update({},update,options).exec(cb);
}
其中参数更新和选项如下:
const update = { $push: { "defaultads": content }};
const options = { multi: true};
它似乎运行并在控制台上提供以下输出:
{ n: 1, nmodified: 1, ok: 1 }
但在数据库的任何文档中根本没有推送。 我检查过 : 1)我是否正在推进正确的数据库。 2)是否传递了正确的值 但是我无法找到我错的地方。
我是nodejs的新手,非常感谢解决这个问题的指导。 提前谢谢。
答案 0 :(得分:0)
我正在给出一个简单的代码,满足您的全面要求。首先使用此文件创建一个config.js
,您将连接到mongodb.Here是代码
module.exports = {
'secretKey': '12345-67890-09876-54321',
'mongoUrl' : 'mongodb://localhost:27017/product'
}
接下来创建一个models
文件夹。将此架构保留在此模型文件夹中。我把它命名为product.js
。这是代码
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var imageSchema = new Schema({
imagepath:{
type:String
}
});
var nameSchema = new mongoose.Schema({
productName:{type: String},
productPrice:{type: Number},
imagePaths:[imageSchema]
});
module.exports = mongoose.model("product", nameSchema);
接下来创建一个routes
文件夹,并将此路由代码保留在此文件夹中,我将其命名为route.js
。这是代码
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Product = require('../models/product');
var app = express();
var Router = express.Router();
Router.use(bodyParser.json());
Router.get('/product',function(req,res){
Product.find({}, function (err, product) {
if (err) throw err;
res.json(product);
});
})
Router.post('/productData',function(req, res, next){
Product.create(req.body, function (err, product) {
if (err) throw err;
console.log('Product Data created!');
var id = product._id;
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Added the product data with id: ' + id);
});
})
Router.post('/subdocument',function (req, res, next) {
Product.find({},function (err, result) {
if (err) throw err;
for(var i=0;i<result.length;i++){
result[i].imagePaths.push(req.body);
result[i].save(function (err, ans) {
if (err) throw err;
console.log('SubDocument created!');
});
}
res.send("Successfully added");
});
})
module.exports = Router;
下一个服务器代码我将其命名为app.js
。这是代码
var express = require('express');
var bodyParser = require('body-parser');
var Product = require('./models/product');
var mongoose = require('mongoose');
var config = require('./config');
mongoose.connect(config.mongoUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log("Connected correctly to server");
});
var app = express();
var route=require('./routes/route');
app.use('/route',route);
app.listen(3000,function(){
console.log("Server listening on 3000");
});
以node app.js
运行服务器。
<强> API的强>