MongoError unknown top level operator: $set

匿名 (未验证) 提交于 2019-12-03 00:57:01

问题:

When I do this:

return scores.updateQ({_id:score._id}, {     $set:{"partId":partId,"activityId":activityId},     $unset:{topicType:'',topicId:'',courseId:''} }, {strict:false}) 

Where partId and activityId are variables, defined elsewhere,

I get

{ name: 'MongoError',   message: 'unknown top level operator: $set',   index: 0,   code: 2,   errmsg: 'unknown top level operator: $set' } 

This answer says

"The "unknown top level operator" message means that the operator has to appear after the field to which it applies."

But the documentation says you can do it the way I'm doing it

So maybe there's something else wrong?

回答1:

The problem is that you're using the syntax for the wrong update method. You should be using this method's syntax, assuming that scores is a document.

return scores.updateQ({     $set: { "partId": partId, "activityId": activityId},     $unset: { topicType: '', topicId: '', courseId: ''} }, { strict: false }); 

Also, in Mongoose, it uses $set by default, so this should be equivalent:

return scores.updateQ({     partId: partId,     activityId: activityId,     $unset: { topicType: '', topicId: '', courseId: ''} }, { strict: false }); 

EDIT:

My assumption is that scores is a document (an instance of the Model):

var schema = new Schema({}); var Scores = mongoose.model('Scores', schema); var scores = new Scores({}); 

Both Scores.update and scores.update exist, but the syntax is different, which may be what's causing your error. Here's the difference:

// Generic update Scores.update({ _id: id }, { prop: 'value' }, callback);  // Designed to update scores specifically scores.update({ prop: 'value' }, callback); 

NOTE:

If these assumptions are not correct, include more context in your answer, like how you got there.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!