我在这里找到很多很棒的答案,例如this回答this。但我不能让它工作......
我在id为的查询中尝试了ObjectId("55cf816559d2fc8d0e6c14a8")
。
当robotmongo运行它时,此查询有效:
db.getCollection('events').update(
{ "_id": ObjectId("55cf816559d2fc8d0e6c14a8") },
{ "$pull": { "workers" : { "_id": ObjectId("55cf89ac7cba1d0a10ca86c7")}}},
false,
true
)
旁注,错误是什么,是真的吗?
这是我目前的代码
event.update(
{'_id': "55cf816559d2fc8d0e6c14a8"},
{ "$pull": { "workers" : {_id: "55cf89ac7cba1d0a10ca86c7"}}},
function(err, result) {
console.log(err);
console.log(result);
}
);
我没有收到任何错误,结果等于1.
答案 0 :(得分:1)
适合我。你必须以不同的方式做错事情:
var async = require('async'),
mongoose = require('mongoose'),
Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/test');
var workerSchema = new Schema({
name: String
});
var eventSchema = new Schema({
name: String,
workers: [workerSchema]
});
var Event = mongoose.model( 'Event', eventSchema );
async.series(
[
function(callback) {
Event.remove({},function(err) {
callback(err);
});
},
function(callback) {
var event = new Event({
_id: "55cf816559d2fc8d0e6c14a8",
name: "Great thing"
});
event.workers.push({
_id: "55cf89ac7cba1d0a10ca86c7",
name: "Worker1"
});
event.save(function(err,event) {
console.log(event);
callback(err);
});
},
function(callback) {
Event.findOneAndUpdate(
{ "_id": "55cf816559d2fc8d0e6c14a8" },
{ "$pull": { "workers": { "_id": "55cf89ac7cba1d0a10ca86c7" } } },
{ "new": true },
function(err,event) {
console.log(event)
callback(err);
}
);
}
],
function(err) {
if (err) throw err;
mongoose.disconnect();
}
);
预期输出:
{ __v: 0,
_id: 55cf816559d2fc8d0e6c14a8,
name: 'Great thing',
workers: [ { _id: 55cf89ac7cba1d0a10ca86c7, name: 'Worker1' } ] }
{ _id: 55cf816559d2fc8d0e6c14a8,
name: 'Great thing',
__v: 0,
workers: [] }