gpt4 book ai didi

node.js - 批量更新 - BulkWriteResult.nMatched 和 BulkWriteResult.nModified 返回 0

转载 作者:太空宇宙 更新时间:2023-11-04 00:41:59 27 4
gpt4 key购买 nike

我的主 server.js 代码,我在其中启动服务器并连接到 mongoDb 服务器

if(process.env.MONGOLAB_URI) {
mongoose.connect(process.env.MONGOLAB_URI);
} else {
mongoose.connect("mongodb://localhost/itrack");
}

global.db = mongoose;

mongoose.connection.on('open', function() {
// This line is getting printed here
console.log('Mongoose opened.');
});
// When successfully connected
mongoose.connection.on('connected', function () {
console.log('Worker ' + process.pid + ' is alive!');
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port:', app.get('port'));
});
});

// If the connection throws an error
mongoose.connection.on('error',function (err) {
console.log('Mongoose default connection error: ' + err);
process.exit(0);
});

// When the connection is disconnected
mongoose.connection.on('disconnected', function () {
console.log('Mongoose default connection disconnected');
});

现在在我的controller/customer/router.js Controller 文件中,

router.put("/addstud/:route", function(req,res,next) {

var custId = req.user.id;
var studList = req.body;
var route = req.params.route;

db.connection.on('open', function() {
// Never goes inside this As i have to bulk Update Operation
console.log('Mongoose opened.');
});

db.connection.once('open',function(err,conn) {
// Nor this
}

});

var bulk = Student.collection.initializeUnorderedBulkOp();

// this simple code is not working
bulk.find({_id:'56f940172681fda5c6536a4d'})
.updateOne( {name:'test'});

bulk.execute(function(err, result) {
if(err) {
console.log("ERROR WHILE INSERTING "+err);
} else {
// This line is getting printed means no error but nothing changed in DB
console.log("RESULT "+result.mMatched); // 0 ! HOW ????????
}
});

但在同一个类中,我可以使用 Mongoose 模型轻松检索数据并将数据添加到数据库。

最佳答案

您必须转换对象中的 id。像字符串一样使用它是行不通的。这样做:

const restful = require('node-restful');
const mongoose = restful.mongoose;

let id = new mongoose.Types.ObjectId('56f940172681fda5c6536a4d');
let obj = {"_id": id};

// And then

bulk.find({_id:'56f940172681fda5c6536a4d'}).updateOne( {name:'test'});

关于node.js - 批量更新 - BulkWriteResult.nMatched 和 BulkWriteResult.nModified 返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36276578/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com